1.客户端编写
(1).要有一个ip+port作为连接的地址 ip_port=('127.0.0.1',8098)
(2).socket的connect方法连接地址
(3).sendall(bytes(inp,'utf8'))来发送客户端的消息
(4).recv(1024)接受服务端的消息,
import socket ip_port=('127.0.0.1',8098) sk = socket.socket() sk.connect(ip_port) print('客户端启动.....') While True: inp = input(">>>") if inp == 'exit': break sk.sendall(bytes(inp,'utf8')) server_response = sk.recv(1024) print(str(server_response,'utf8')) sk.close()
2.服务端编写
(1).服务端使用socketserver包,直接编写的Myserver继续socketserver.BaseRequestHandler
socketserver中会实例话Myserver,调用run(),handle()等方法
(2).建立相关的连接 使用socketserver.ThreadingTCPServer(地址,Myserver)
调用server_forever()
import socketserver class Myserver(socketserver.BaseRequestHandler): def handle(self): print('服务端启动....') while True: conn = self.request print(self.client_address) while True: client_data = conn.recv(1024) print(str(client_data,'utf8')) print('waiting...') server_response = input('>>>>') conn.sendall(bytes(server_response,'utf8')) conn.close() if __name__ == "__main__": server = socketserver.ThreadingTCPServer(('127.0.0.1',8098),Myserver) #创建socket链接 server.serve_forever()