socketserver Posted on 2016-10-19 TCP服务器端1234567891011121314151617#!/usr/bin/env pythonimport socketserverfrom time import ctimeHOST = ''PORT = 21567ADDR = (HOST, PORT)class MyRequestHandler(socketserver.StreamRequestHandler): def handle(self): print('...connected from: ', self.client_address) self.wfile.write('[%s] %s'.encode('utf-8') % (bytes(ctime(), 'utf-8'), self.rfile.readline()))tcpServ = socketserver.TCPServer(ADDR, MyRequestHandler)print('waiting for connection...')tcpServ.serve_forever() 对handle进行了重写,原本为 1def handle(self):pass TCP客户端123456789101112131415161718192021#!/usr/bin/env pythonfrom socket import *HOST = 'localhost'PORT = 21567BUFSIZ = 1024ADDR = (HOST, PORT)while True: tcpCliSock = socket(AF_INET, SOCK_STREAM) tcpCliSock.connect(ADDR) data = input('> ') if not data: break tcpCliSock.send(bytes(data + "\n", "utf-8")) data = tcpCliSock.recv(BUFSIZ) if not data: break print(data.strip().decode('utf-8')) tcpCliSock.close() 在这个例子中,连接了服务器两次