查找了许多资料,实现了客户端与服务器端的连接,通过虚拟机进行测试
服务器端IP:192.168.37.129 端口1122
客户端IP: 192.168.37.1 端口1122
Server:
#coding:utf-8 from socket import * class Dserver(): def __init__(self): self.HOST = ‘192.168.37.129‘ self.PORT = 1122 self.BUFSIZE = 1024 self.ADDR = (self.HOST, self.PORT) self.sock = socket(AF_INET, SOCK_STREAM) self.sock.bind(self.ADDR) def listener(self): self.sock.listen(5) STOP_CHAT = False while not STOP_CHAT: print(‘等待接入,侦听端口:%d‘ % (self.PORT)) topClientSock, addr = self.sock.accept() print(‘接受连接,客户端地址:‘,addr[0]) while True: try: data = topClientSock.recv(self.BUFSIZE) except: topClientSock.close() print("服务器关闭!") break if not data: print("数据为空") break s=‘把服务器收到的从%s发送给我的信息:%s 发回来‘ %(addr[0],data.decode(‘utf-8‘)) print(s) topClientSock.send(s.encode(‘utf-8‘)) print(data.decode(‘utf-8‘)) STOP_CHAT=(data.decode(‘utf-8‘).upper()=="QUIT") if STOP_CHAT: break topClientSock.close() self.sock.close() if __name__ == ‘__main__‘: serverDemo = Dserver() serverDemo.listener()
Client:
#coding:utf-8 from socket import * class Dclient(): def __init__(self): self.HOST = ‘192.168.37.129‘ self.PORT = 1122 self.BUFSIZE = 1024 self.ADDR = (self.HOST, self.PORT) def listener(self): self.client = socket(AF_INET,SOCK_STREAM) self.client.connect(self.ADDR) while True: data = input(‘>‘) if not data: break self.client.send(data.encode(‘utf-8‘)) print(‘发送消息给%s: %s‘ % (self.HOST, data)) if data.upper() == ‘QUIT‘: break data = self.client.recv(self.BUFSIZE) if not data: break print(‘接受的消息 %s‘ % (data.decode(‘utf-8‘))) if __name__ == ‘__main__‘: clientDemo = Dclient() clientDemo.listener()
测试数据:
时间: 2024-10-19 00:41:07