用python分别写tcp通信的服务端和客户端代码
时间: 2023-11-11 13:07:09 浏览: 116
当然可以,以下是Python的TCP通信服务端和客户端代码供您参考:
服务端代码:
import socket
HOST = ''
PORT = 8888
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(1)
while True:
client_socket, client_address = server_socket.accept()
print('Incoming connection from:', client_address)
while True:
data = client_socket.recv(1024)
if not data:
break
client_socket.sendall(data)
client_socket.close()
客户端代码:
import socket
HOST = '127.0.0.1'
PORT = 8888
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
client_socket.sendall(b'Hello, server!')
data = client_socket.recv(1024)
print('Received:', data.decode())
client_socket.sendall(b'How are you?')
data = client_socket.recv(1024)
print('Received:', data.decode())
client_socket.sendall(b'Goodbye!')
data = client_socket.recv(1024)
print('Received:', data.decode())
client_socket.close()
请注意,以上代码仅供参考,您需要根据您的具体要求进行修改和优化。
阅读全文