python--DenyHttp項目(1)--socket編程:客戶端與服務器端
阿新 • • 發佈:2017-07-23
brush accept acc -- highlight 發送消息 src size 接受
查找了許多資料,實現了客戶端與服務器端的連接,通過虛擬機進行測試
服務器端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()
測試數據:
python--DenyHttp項目(1)--socket編程:客戶端與服務器端