Python socket学习笔记(三)
之前都是客户端对服务器的单线程操作。接下来学习 SocketServer 多线程
SockServer
class SocketServer.BaseServer SocketServer.BaseRequestHandler The request handler class must define a new handle() RequestHandler.Handle() This function must do all the work required to service a request. The default implementation dose nothing.Several instance attributes are available to it; the request is available as self.request;the clinet address as self.client_address;and the server instance as self.server, in case it needs access to per-server information RequestHandler.setup() Called before the handle() method to perform any initialization actions required. The default implementation does nothing. BaseServer.serve_forever(poll_interval=0.5) Handle requesets until an explicit shutdown() request. Poll for shutdown every poll_interval seconds. Ignores self.timeout.If you need to do periodic tasks,do them in another thread.
多线程的连接过程:
SocketServer 例子
服务器端
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
while 1:
self.data=self.request.recv(1024).strip()
print ("{} wrote:".format(self.client_address[0]))
if not self.data:break
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST,PORT = "localhost",9999
server = SocketServer.ThreadingTCPServer((HOST,PORT),MyTCPHandler)
server.serve_forever()
client (也可以使用之前的客户端程序,只要改下端口即可)
import socket,sys HOST,PORT = "localhost",9999 data = " ".join(sys.argv[1:]) #create a socket (SOCK_STREAM means a TCP socket) sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: #Connect to server and send data sock.connect((HOST,PORT)) sock.sendall(data + "\n") # Receive data from the server and shutdown received = sock.recv(1024) finally: sock.close() print("Sent: {}".format(data)) print("Received: {}".format(received)