Network Programming [The second] based udp socket programming protocol

Udp socket programming under the agreement

No link is a .udp unreliable

The chapter on the tcp protocol is reliable, there will be feedback information to confirm the completion of the exchange of information or not

Udp protocol based on written service and client, their duties, regardless of whether the other received information, simply send yourself a can

II. Client

Import socket 

# buy a mobile phone - Family Sockets | Port Protocol 
Phone = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
 # server address 
ip_port = ( ' 127.0.0.1 ' , 8001 )
 # achieve multiple transmit information 
while true:
     # customize a message 
    MSG = iNPUT ( ' enter a message: ' )
    # If the information is null, the program can cause stuck, if a skip this case is determined 
    if  Not MSG:
         Continue 
    # send information specifying the phone is turned on data addresses and server 
    phone.sendto (msg.encode ( ' UTF-. 8 ' ), for ip_port)
     Print ( 'Sending information to the server: ' , MSG)
     # receiving feedback information received by a specified amount 
    Data, addr = phone.recvfrom (10 )
     Print ( " successfully received feedback information to the server ' )
 # shutdown 
phone.close ()

 

III. Server

Import socket 

# buy a mobile phone - Family Sockets | Port Protocol 
Phone = socket.socket (socket.AF_INET, socket.SOCK_DGRAM) 

# buy phone cards - a listen address - ip | port number 
phone.bind (( ' 127.0.0.1 ' , 8001 )) 

# multiple sending and receiving information  
the while True:
     # phone receives information specifying a number of information received after turning 
    # returns the client address and data 
    data, addr = phone.recvfrom (10 )
     Print ( ' received customer information for the end: ' , the Data)
     # after receiving the message, a message back to the client side to tell that he has successfully received 
    phone.sendto (the Data, addr)
     Print ( ' success to a client sends a feedback message ') 

    # After completion of the operation to turn off all the link, and then shut down 
link.close () 
phone.close ()

 

Four Summary - simplified

Client:

socket = cs ()    # create a client socket 
comm_loop:       # communication cycle 
    cs.sendto () / cs.recvfrom ()    # Dialogue (send / receive) 
cs.close ()                       # close the client socket

 

Server:

SS = socket 1 ()    # create a server socket 
2 ss.bind ()        # bind server socket 
3 inf_loop:        # server infinite loop 
4 cs = ss.recvfrom () / ss.sendto () # Dialogue (receive and transmit) 
. 5 ss.close ()                          # close server socket

 

Guess you like

Origin www.cnblogs.com/xxp1624/p/11241611.html