下面是一个简单的例子,演示如何在Python中启动TCP服务并监听连接,以及如何从客户端发送消息:
TCP服务端代码:
import socket
HOST = '192.168.6.211'
PORT = 8888
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen()
print(f'Server is listening at {HOST}:{PORT}')
while True:
client_socket, client_address = server_socket.accept()
print(f'Client connected from {client_address}')
message = client_socket.recv(1024).decode('utf-8')
print(f'Received message from client: {message}')
response = 'Hello from server!'
client_socket.send(response.encode('utf-8'))
client_socket.close()
TCP客户端代码:
import socket
HOST = '192.168.6.211'
PORT = 8888
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
message = 'Hello from client!'
client_socket.send(message.encode('utf-8'))
response = client_socket.recv(1024).decode('utf-8')
print(f'Received response from server: {response}')
client_socket.close()
这个例子中,服务端首先创建一个socket对象并绑定地址和端口,然后开始监听连接。当客户端连接到服务器时,服务端接受客户端的连接请求并打印客户端地址,然后接收从客户端发送过来的消息,并回复一条消息。客户端首先创建一个socket对象并连接到服务器,然后发送一条消息,并等待接收回复消息。