[本文出自天外归云的博客园]
目标:实现客户端与服务端的socket通信,消息传输。
客户端
客户端代码:
from socket import socket,AF_INET,SOCK_STREAM #服务端的ip地址
server_ip = '127.0.0.1'
#服务端socket绑定的端口号
server_port = 20000 if __name__ == '__main__':
while True:
str_msg = input("请输入要发送信息:")
if str_msg != "":
bytes_msg = bytes(str_msg, encoding = "gbk")
client = socket(AF_INET,SOCK_STREAM)
client.connect((server_ip,server_port))
client.send(bytes_msg)
print(str(client.recv(8192),encoding="gbk"))
client.close()
客户端(Mac系统)运行截图:
服务端
服务端代码:
from socketserver import BaseRequestHandler, TCPServer #指定接收消息的客户端ip列表
target_clients = ["10.235.0.109"] class EchoHandler(BaseRequestHandler):
def handle(self):
for target_client in target_clients:
if target_client in self.client_address:
print('Got connection from', self.client_address)
msg = self.request.recv(8192)
if not msg:
break
ret_msg = bytes("自动回复:消息已收到!", encoding = "gbk")
self.request.send(ret_msg)
print(str(msg, encoding = "gbk"))
break if __name__ == '__main__':
from threading import Thread
NWORKERS = 16
#绑定socket服务端所在ip和端口号
serv = TCPServer(('', 20000), EchoHandler)
for n in range(NWORKERS):
t = Thread(target=serv.serve_forever)
t.daemon = True
t.start()
serv.serve_forever()
服务端(Windows系统)运行截图,注意要设置cmd活动页代码为936(chcp 936)方可显示中文,设置cmd属性中的字体为点阵字体: