python3-TCP服务器和客户端(socketserver类),,#!/usr/bin


#!/usr/bin/env python3import socketimport sysHOST="localhost"PORT=21200ADDR=(HOST,PORT)# Create a socket (SOCK_STREAM means a TCP socket)with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: # 连接服务器 sock.connect(ADDR) data=input(‘==>‘) sock.sendall(bytes(data + "\n", "utf-8")) # Receive data from the server and shut down received = str(sock.recv(1024), "utf-8")print("Sent: {}".format(data))print("Received: {}".format(received))#!/usr/bin/env python3import socketserver from time import ctimeHOST=‘‘PORT=21200ADDR=(HOST,PORT)class MyTCPHandler(socketserver.StreamRequestHandler): def handle(self): print("接受{0}连接...".format(self.client_address)) self.data = self.rfile.readline().strip() print("{} 发来消息:".format(self.client_address[0])) print(self.data) # self.wfile是一个类似文件的对象,用于写回客户端 self.wfile.write(bytes("{0}:{1} ".format(ctime(),self.data),‘utf-8‘))if __name__ == "__main__": # Create the server, binding to localhost on port 9999 with socketserver.TCPServer(ADDR, MyTCPHandler) as server: print("等待连接...") #激活服务器,直到按ctrl+c退出 server.serve_forever()
bogon:python3 myhaspl$ python3 1-c.py==>hhhhSent:     hhhhReceived: Sun Sep 16 12:47:01 2018:b‘hhhh‘ 下面是服务器端运行状态:等待连接...接受(‘127.0.0.1‘, 50751)连接...127.0.0.1 发来消息:b‘hi‘接受(‘127.0.0.1‘, 50752)连接...127.0.0.1 发来消息:b‘hhhh‘

python3-TCP服务器和客户端(socketserver类)

评论关闭