python怎样建立socket服务器

展开全部下面的例子是多线程实现的socket服务器:import socketimport threadingclass ThreadedServer(object):def __init__(self, host, port):self.host = hostself.port = portself.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)self.sock.bind((self.host, self.port))def listen(self):self.sock.listen(5)while True:client, address = self.sock.accept()client.settimeout(60)threading.Thread(target = self.listenToClient,args = (client,address)).start()def listenToClient(self, client, address):size = 1024while True:try:data = client.recv(size)if data:# Set the response to echo back the recieved dataresponse = dataclient.send(response)else:raise error(Client disconnected)except:client.close()return Falseif __name__ == "__main__":while True:port_num = input("Port? ")try:port_num = int(port_num)breakexcept ValueError:passThreadedServer(,port_num).listen()