Python uses sockets to implement TCP connections, send and receive data
Preparation work for environmental construction:
1. Install Python: If you have not already installed Python, please visit the official Python website( https://www.python.org/ )Download and install the latest version suitable for your operating system. Please ensure to add Python to the environment variable.
2. Ensure that the required class libraries are installed: As we will use the socket class library, which comes with Python, there is no need for additional installation.
Dependent class libraries:
In this example, the class library we are using is the socket class library that comes with Python.
Example code:
The following is a simple example program that demonstrates how to use sockets to achieve basic TCP connections, send and receive data.
python
import socket
def create_tcp_socket():
'''
Create TCP Socket
'''
return socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect_socket(sock, host, port):
'''
Connect to the specified host and port
'''
sock.connect((host, port))
def send_data(sock, data):
'''
send data
'''
sock.sendall(data.encode())
def receive_data(sock, buffer_size=1024):
'''
receive data
'''
data = sock.recv(buffer_size).decode()
return data
def close_socket(sock):
'''
Close Socket Connection
'''
sock.close()
if __name__ == '__main__':
#Setting Up Hosts and Ports
HOST = '127.0.0.1'
PORT = 8080
#Create TCP Socket
tcp_socket = create_tcp_socket()
#Connect to the specified host and port
connect_socket(tcp_socket, HOST, PORT)
#Sending data
message = 'Hello, server!'
send_data(tcp_socket, message)
#Receiving data
response = receive_data(tcp_socket)
print('Received:', response)
#Close Socket Connection
close_socket(tcp_socket)
Summary:
In Python, using the socket class can facilitate TCP connections, sending, and receiving data. By creating a TCP socket and connecting to the specified host and port, then sending and receiving data, and finally closing the socket connection, TCP communication can be completed.