python network programming without socket module
1. Simple use of the socket module to develop a simple command-line tool for example, as follows
1.1 Socket client-side code
1 #-*-coding:utf-8-*-2 #Author:wong Du3 4 ImportSocket5 6 #Create a Socket object7Client =Socket.socket ()8 #establish a connection to the server side9Client.connect (('localhost', 9494) )Ten One A whileTrue: - #Get user Input -Cli_send = input (">>:"). Strip () the #Determine if user input is empty - ifLen (cli_send) = =0: - Continue - + #send data to server side, must be bytes type -Client.send (Cli_send.encode (encoding="Utf-8")) + A #receive server-side returned data, 102400 of the size of the received data atdata = CLIENT.RECV (102400) - #to view the data received - Print(Data.decode ()) - - #Close Connection -Client.close ()
1.2 Socket server-side code
#-*-coding:utf-8-*-#Author:wong DuImportOSImportSocket#Create a socket connectionServer =Socket.socket ()#bind the appropriate IP and port numberServer.bind (('localhost', 9494) )#start listening, 5 to monitor the maximum number of connectionsServer.listen (5)Print("I'm going to start listening.")#wait for the request to connect, stuck; Conn is the connection object, addr is the connection identityPrint("waiting for client to request connection ~ ~") conn, addr=server.accept ()Print("Receive client connection, identity is:", addr) whileTrue:#receives the command sent by the client, 1024 is the size of the received datadata = CONN.RECV (1024) #executes the command and receives the command to return the resultres =Os.popen (Data.decode ()). Read ()#if the command has no return result if notRes:res='Invalid command.' #Send command return result to client, data must be bytes typeConn.send (Res.encode (encoding='Utf-8'))#Close ConnectionServer.close ()
The socket module in Python