These two days, learning the Python socket Programming (Linux version), I found a lot of information is Linux, but Python is obviously cross-platform, so, I based on the Linux version of the material to write a little windows, I hope to be a little help to everyone, In addition : I vegetable a piece, if there is a problem, welcome to correct, thank you for your cooperation.
First analyze the approximate process:
Once the connection is established, (multiple or one) the client sends the command line to the server;
Second, the server receives the command line, executes the command;
Third, the server will implement the results of feedback to the client;
Four, several times to carry out the above process;
So, how does python solve these problems?
One, the connection part, because the server side needs to process multiple client requests simultaneously, therefore needs to use the multi-threaded concurrency operation, the python provides the socketserver to solve the server multithreading problem, for the client, uses the Python to provide the single-threaded socket to be able to send and receive the data ;
Second, execute the command sent, Python provides an OS this module to solve (Linux using Commads module), specifically, because we need to send back the data returned to the client, so we need to use Cmd_result = Os.popen ("command"). Read ( )。
Third, by the 2nd: Obviously, we need to return to the client is Cmd_result.
Four, to execute multiple times, you can use the Python loop to execute;
Note: The approximate process and the Python solution have been analyzed, but the details of the program, such as using Sendall () can send all the data at once, and if you use Send () you may need to loop through the data, for example, to empty the data and the syntax of Python. , the author is not verbose here, if there is doubt, welcome message discussion, or self-Baidu to solve, the following is the code:
Server:
#serverimport Socketserver, Osclass Mytcphandler (Socketserver.baserequesthandler): def handle (self): while True: self.data = Self.request.recv (1024x768). Strip () print "{}wrote:". Format (Self.client_address[0]) if Not self.data: print ' clilent%s is dead! '% self.client_address[0] break cmd_result = Os.popen (self.data) . read (); If Len (Cmd_result.strip ())! = 0: self.request.sendall (Cmd_result) else: self.request.sendall (' not Found the command: ' + self.data ' if __name__ = = ' __main__ ': HOST, PORT = ' 127.0.0.1 ', 3333 server = Socketserver. Threadingtcpserver (HOST, PORT), Mytcphandler) server.serve_forever ()
Client:
#clientimport sockethost = "127.0.0.1" PORT = 3333s = Socket.socket (socket.af_inet, socket. Sock_stream) S.connect ((HOST, PORT)) while 1: cmd = raw_input (' Your command: '). Strip () s.sendall (cmd) result = S.recv (1024x768) print results.close ()
Under Windows, Python implements SSH based on Socketserver emulation (multi-threaded version)