下面是一个简单的例子,演示如何在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对象并连接到服务器,然后发送一条消息,并等待接收回复消息。
文章来源地址https://www.toymoban.com/news/detail-547991.html文章来源:https://www.toymoban.com/news/detail-547991.html
到了这里,关于Python启动TCP服务并监听连接,从客户端发送消息的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!