Python Day31: socket cover bytes, TCP protocol and common built-in functions, and the server and the client standard tags

# # Socket 

`` `Python 
Socket socket is: 
as an end TCP connection, which socket end is called CP with the port number on the host with the IP address of the host 
which is a communication network during an abstract representation of the endpoint including five kinds of information network communication be required: protocol port to connect to the protocol, the IP address of the local host, local port protocol process, the remote host's IP address, the remote process. 
# Network communication and is connected, there are three main parameters: destination IP address of the communication using a transport layer protocol (TCP or UDP) and port number used. Socket is intended to "socket." By combining these three parameters, with a "socket" the Socket binding, the application layer and the transport layer can be a socket interface, a communication process or to distinguish between different applications from a network connection, data transmission is concurrent service 
is a packaged module, the module is to learn to use 
socket divided into two types   
AF_UNIX: inter-process communication 
AF_INET: network communication  
needs clear: on the network protocol concepts and socket, are the same for all programming languages the only difference is a function of the names of the different programming languages 
to be clear: whether it is a client server socket object use is 
 
`` 

# in the # socket commonly used functions 

`` `python 
server socket function 
s.bind () bind (host, port number) to the socket 
s.listen () to start listening TCP
s.accept () passive acceptance of client TCP connections (blocking) waiting for the arrival of connected 

client socket function 
s.connect () initiative to initialize TCP server connections 
s.connect_ex () connect () function in the extended version, error return error code, rather than throwing an exception 

public use socket function 
s.recv () receives TCP data 
when s.send () TCP data transmission (send data to be transmitted is greater than the remaining buffer space has an end, the data lost, not finished) 
when s.sendall () to send a complete TCP data (essentially circular call send, SendAll data to be transmitted is greater than the remaining space hexyl side cache, data is not lost, the call to send the cycle until finished) 
s.recvfrom () receiving UDP data 
s.sendto () sends UDP 
s.getpeername () is connected to the distal end of the address of the current socket 
s.getsockname () socket address current 
s.getsockopt () returns the specified socket parameters 
s.setsockopt () setting parameters of the socket 
S.CLOSE () closes the socket 

lock socket method for 
blocking s.setblocking () provided with non-blocking mode socket 
s. setTimeout () set the timeout blocking socket operation
s.gettimeout () to get the timeout blocking socket operation 

`` `

 <the p-style = " Color: Red " #> Note TCP must start the server and then start the client, or the client because the server can not be linked directly to an error! </ The p-> # # TCP server 
`` `Python Import socket 
ip_port = ( ' 127.0.0.1 ' , 8081) # telephone card 
BUFSIZE = 1024 
S = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # buy mobile phones 
s.bind (ip_port) # phone card 
s.listen (5)      # phone standby the while True:                          # new reception cycle link can not stop to answer the phone 
    conn, addr = s.accept ()            





Mobile phone 
    # Print (Conn) 
    # Print (addr) 
    Print ( ' = (Receiving the call from% s ' % addr [0])
     the while True:                          # new communication cycle, communication can continue, messaging 
        MSG = conn.recv (the BUFSIZE)              # Listen message, listen 
        Print (MSG, type (MSG )) 
        conn.send (msg.upper ())           # message, speak 
    conn.Close ()                     # hang 
S.CLOSE ()                        # phone off 


`` ` 

# # TCP client 

` `` Python 
Import socket 
ip_port' 127.0.0.1 ' , 8081 ) 
the BUFSIZE = 1024 
S = socket.socket (socket.AF_INET, socket.SOCK_STREAM) 
s.connect_ex (for ip_port)            # dialed 

the while True:                              # new communication cycle, the client may continue to send and receive messages 
    INPUT = MSG ( ' >>: ' ) .strip ()
     IF len (MSG) == 0: Continue 
    s.send (msg.encode ( ' UTF-. 8 ' ))          # message, speak (only send bytes type) 
    
    Feedback = s.recv (the BUFSIZE)                            # received message, listen 
    print (feedback.decode ( ' UTF-. 8 ' )) 
S.CLOSE ()                                        # hang 

` 

When the client and the server call a successful link, if one is not performed close, but directly forcibly terminates the program (or an exception is encountered forced termination), will lead to other problems sent 

under linux, does not throw a party will lead to the received data, recv methods continue to receive an empty message, resulting in an infinite loop 

enable applications to different platforms to work on, that these two issues need to be addressed are 

solutions are as follows: 

`` `Python 
Import Socket 
for ip_port = ( ' 127.0.0.1 ' , 8081 ) 
the BUFSIZE = 1024 
S = socket.socket (socket.AF_INET, socket.SOCK_STREAM) 
s.bind (for ip_port ) 
s.listen ( 5 )    
 the while True:                        
    conn, addr = s.accept ()           
     the while True:                         
         the try : 
            msg = conn.recv (BUFSIZE)             
             # Linux does not throw an exception, will receive an empty message, to be judged here 
            IF  not msg: 
                conn.Close () 
                BREAK 
            Print (msg, of the type (msg)) 
            conn.send (msg.upper ())         
       the except ConnectionResetError:
             # long as it means an exception occurs, and the other closed, the server closes the corresponding link 
            conn.Close ()
             BREAK 
    conn.Close ( )               
S.CLOSE ()                        

`` `

At this point TCP communications program template is complete, you can continue to receive new link, constantly sending and receiving messages, and the client will not be forced to close because of abnormal exit!

 

Guess you like

Origin www.cnblogs.com/huhongpeng/p/10960223.html