首页 > 代码库 > python--DenyHttp项目(1)--socket编程:客户端与服务器端
python--DenyHttp项目(1)--socket编程:客户端与服务器端
查找了许多资料,实现了客户端与服务器端的连接,通过虚拟机进行测试
服务器端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 = http://www.mamicode.com/topClientSock.recv(self.BUFSIZE)"服务器关闭!") 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()
测试数据:
python--DenyHttp项目(1)--socket编程:客户端与服务器端
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。