Use socket to implement multiple connections and ssh functions, and socket to implement multiple ssh

Source: Internet
Author: User

Use socket to implement multiple connections and ssh functions, and socket to implement multiple ssh
I. Preface

In the previous article, we already know that the client connects to the server through socket for a data transmission. How can we implement multiple data occurrences on the client? But does the server accept multiple clients?

2. Send Chinese Information

In python3, the socket can only send bytes data, and the bytes type can only represent the value of the 0-2 25 ASCII code, and cannot represent Chinese. Therefore, when we need to send Chinese characters, encoding and decoding are required.

Client:

Import socket # client # declare the protocol type and generate the socket object client = socket. socket () # client. connect ('localhost', 8888) # python3 receives byte stream data msg = input ('>> :'). strip () client. send (msg. encode ('utf-8') # first encode it into UTF-8 format data = client. recv (1024) #1024 bytes of data print (data) print (data. decode ())
View Code

Server:

Import socket # declared protocol type server = socket. socket () # bind a local NIC (select multiple NICS) and port server. bind ('localhost', 8888) # Listen to the port server. listen () # listener # conn is a connection instance generated for the client on the server after the client is connected # address is the client's hostaddr, portconn, address = server. accept () print ("Enter wait time .... ") # Wait # print (conn, address) print (" received connection .... ") # receive data data_server = conn. recv (1024) print ('receive: ', data_server.decode () # decode # Return a value conn. send (data_server)
View Code 3. Socket implements multiple connections

This example needs to be tested in Linux. In windows, multiple clients are connected at the same time (that is, multiple socket_client.py programs are run at the same time). If one of the clients is disconnected, the server reports an error. In Linux, The python version is 3.5.

Example code:

Client:

Import socket # client # declare the protocol type and generate the socket object client = socket. socket () # client. connect ('localhost', 8888) # python3 receives byte stream data while True: msg = input ('>> :'). strip () if len (msg) = 0: # The input cannot be empty. send (msg. encode ('utf-8') data = client. recv (1024) #1024 bytes of data print (data) print (data. decode ())
View Code

The input in the case is null (I .e. len (msg = 0). If you do not enter anything, the socket program waits for your input by default, so the program will be stuck.

Server:

#-*-Coding: UTF-8-*-import socket # declare protocol type server = socket. socket () # bind a local NIC (select multiple NICS) and port server. bind ('localhost', 8888) # Listen to the port server. listen (5) # listen while True: conn, address = server. accept () print ("Enter wait time .... ") while True: print (" received connection .... ") # receive data data_server = conn. recv (1024) if not data_server: # determine if the client is disconnected. if not controlled, print ('client is lost... ') break print ('receive:', data_server.decode () # returns a value conn. send (data_server)
View Code

On a Linux server, I have enabled six clients, and each client is disconnected once entered (that is, the client has lost... is displayed ...), the server connects to six clients and receives data.

 

4. Implement the ssh Function

4.1 Test Environment

Server: 172.16.200.49, listening port ('0. 0.0.0 ', 8888), Linux System

Client: win10

4.2 Test code

Server:

#-*-Coding: UTF-8-*-import socketimport OS # declare protocol type server = socket. socket () # bind a local NIC (select multiple NICS) and port server. bind ('0. 0.0.0 ', 8888) # listens to the port server. listen () # listen while True: conn, address = server. accept () print ("Enter wait time .... ") while True: print (" received connection .... ") # receive data data_server = conn. recv (1024) if not data_server: print ('client is lost... ') break res = OS. popen ("{}". format (data_server.decode ())). read () # store and return the result of executing the command # Return the result conn. send (res. encode ('utf-8 '))
View Code

Client:

#-*-Coding: UTF-8-*-import socket # client # declare the protocol type and generate the socket object client = socket at the same time. socket () # client. connect ('2017. 16.200.49 ', 8888) # Server ip address and port # python3 receives byte stream data while True: msg = input (' >> :'). strip () if len (msg) = 0: continue client. send (msg. encode ('utf-8') data = client. recv (1024) #1024 bytes of data print (data. decode ())
View Code

The result is as follows:

  

  

Note: The size of data received and sent by the recv () and send () functions in the socket is limited. If a sending request is too large to be received by the client, it will be stored in the cache first. However, for the next command, the client still receives the data that was not sent by the last command.

4. upload files through analog FTP

In this example, when the server is in a Linux environment, the struck module has some problems.... Currently, it can run normally in win10.

Server:

#-*-Coding: UTF-8-*-import structimport socketclass FtpServer (object): def _ init _ (self, host, port): self. host = host self. port = port def ftp_server (self): # declare the protocol type ftp_server = socket. socket () # bind a local NIC (multiple NICS), Port ftp_server.bind (self. host, self. port) # listening port ftp_server.listen () # listening while True: print ('wait... ') conn, address = ftp_server.accept () while True: file_info = struct. calcsize ('128sl ') buf = conn. recv (file_info) if buf: file_name, file_size = struct. unpack ('128sl ', buf) # Use strip () to delete the extra empty character file_new_name = file_name.decode () appended during packaging (). strip ('\ 00') print ('start sorting ing... ') fw = open (file_new_name, 'wb') received_size = 0 # size of the received file while not received_size = file_size: if file_size-received_size> 1024: r_data = conn. recv (1024) Export ed_size + = len (r_data) else: r_data = conn. recv (file_size-received_size) received_size = file_size fw. write (r_data) fw. close () if _ name _ = '_ main _': server = FtpServer ('localhost', 8888) server. ftp_server ()
View Code

Client:

#-*-Coding: UTF-8-*-import socketimport osimport structclass FtpClient (object): # define an FtpClien class def _ init _ (self, host, port): self. host = host self. port = port def client_push (self): # declare the protocol type and generate the socket object ftp_client = socket. socket () # connect to the ftp_client.connect (self. host, self. port) while True: # Switch the file directory path print ("input file directory path") pwd = input (">> :"). strip () # list file names files_list = OS. listdir ('{}'. format (pwd) for I in files_list: print (I) file_name = input ('input file name :'). strip () file_path = OS. path. join (pwd, file_name) if OS. path. isfile (file_path): file_info = struct. calcsize ('128sl ') # define the packaging rule f_head = struct. pack ('128sl ', file_name.encode ('utf-8'), OS. stat (file_path ). st_size) ftp_client.send (f_head) fo = open (file_path, 'rb') while True: file_data = fo. read (1024) if not file_data: break ftp_client.send (file_data) fo. close () # upload the file ftp_client.send (file_data) # client. close () if _ name _ = '_ main _': client = FtpClient ('localhost', 8888) client. client_push ()
View Code

Result:

  

You can view the uploaded file at the position of socket_server.py.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.