Socket-tcp

# Tcp server 
Import Socket 

Server = socket.socket (socket.AF_INET, socket.SOCK_STREAM)   # Create a socket object server, notices transmission network, data are based on the data stream format tcp protocol 
server.bind (( ' 127.0.0.1 ' , 3000))   # binding ip with Port 
server.listen (. 5)   # capacity pool is declared semijoin. 5 
the while . 1 :
     Print ( ' waiting for clients to connect ... ' ) 
    Conn, client_addr = server.accept ()   # wait for the client to establish the connection 
    the while . 1:   # connection is established the client waits for data coming 
        Print ( " waiting for client ... data transfer ')
         The try : 
            recv_data = conn.recv (1024)   # receives data from the client, the maximum number of bytes per statement receives the data for 1024 
            the send_data = ( ' received: ' + recv_data.decode ( ' UTF-. 8 ' )) .encode ( ' utf-8 ' )   # Do some processing on the received data 
            conn.send (send_data)   # Send the processed data to the client 
        except Exception as e:
             print (e)
             break   # If an exception occurs, such as the client closes the communication loop is exited 
    conn.Close ()   # after completion of the communication cycle, immediately close the current connection, the connection pool from semi client access or waiting for the next new client

 

# Tcp client 
Import Socket 

Client = socket.socket (socket.AF_INET, socket.SOCK_STREAM)   # Create client socket object declared as transmission network, a data stream format data based on the protocol tcp 
the client.connect (( ' 127.0.0.1 ' , 3000))   # statement service side ip and port, to establish a server connected to 
the while . 1 : 
    the send_data = INPUT ( ' data to the server side: ' ) .strip () encode (. ' UTF-. 8 ' )
     IF len (send_data) == 0:
         the Continue   # If the sending is empty, resend 
    client.send (send_data)   # sending data inputted by the client to the server
    = client.recv recv_data (1024)   # of data received from the server, receiving the maximum number of bytes per statement data for 1024 
    Print (recv_data.decode ( ' UTF-. 8 ' ))

 

Guess you like

Origin www.cnblogs.com/caoyu080202201/p/12742042.html