First, we can look at the simplest interactive server and client programs.
Server
Import Socketdef Main (): sock = Socket.socket (socket.af_inet,socket. SOCK_STREAM) sock.bind ((' localhost ', 8000)) Sock.listen (5) while True: print ' 1 ' connection, CLENT_ADDR = Sock.accept () while 1: buf = Connection.recv (1024x768) connection.sendall (' Hi ') print buf connection.close () if __name__ = = ' __main__ ': Main ()
[Server]: After creating the socket, the server will remain blocked, and once a user connects, immediately wait for the user to send the data, and then receive the user sent the data after understanding the return of a character, then the state becomes waiting for the next connection
Client
Import Socketsock = Socket.socket () sock.connect ((' localhost ', 8000)) Sock.settimeout (5) While 1: res = SOCK.RECV ( 1024x768) Print res data = raw_input (' input: ') sock.sendall (data) sock.close ()
[Client]: Go to the server side and send the data continuously, then accept the return.
-------------------------------------------------------------------------------
Then you can see that the server side of the above code can only accept a request at the same time, because there is only one thread to process the code
Then I can do it. The server-side code is replaced by
Import Socketserverclass MyServer (socketserver.baserequesthandler,object): def handle (self): conn = Self.request Conn.sendall (' This was a tast ') flag = True while flag: data = CONN.RECV (1024x768) print " Data: ", data if data = =" Exit ": Flag = True elif data = = ' 0 ': conn.sendall (" The Winter in Comming ") else: conn.sendall ("Please input again") if __name__ = = "__main__": Server01 = Socketserver.threadingtcpserver ((' 127.0.0.1 ', 8080), MyServer) print "Server is running ..." Server01.serve_forever ()
We write a multi-threaded server with the help of the socket's own class, and can send and receive messages
python-Network Programming-03