socket send and receive information

1  # Import socket package 
2  Import Socket
 . 3  
. 4  
. 5  DEF available for purchase ():
 . 6      Print ( " ------ Welcome UDP chat device -------- " )
 . 7      Print ( " 1. Send information " )
 . 8      Print ( " 2. receiving information " )
 . 9      Print ( " of 0. The exit chat device " )
 10  
. 11  DEF send_msg (UDP_SOCKET):
 12 is      DEST_IP = iNPUT ( " enter a destination IP: " )
 13 is     int = dest_port (the INPUT ( " Please enter the destination port: " ))
 14      send_data the INPUT = ( " Please enter the content to be transmitted " )
 15      # sendto (content (target IP, port)) 
16      udp_socket.sendto (send_data.encode ( " GBK " ), (DEST_IP, dest_port))
 . 17  
18 is  
. 19  DEF recv_msg (UDP_SOCKET):
 20 is      # recvfrom (maximum receiving bytes) 
21 is      rece_data = udp_socket.recvfrom (1024 )
 22 is      # to be decoded, or garbled 
23 is      Print ( " % S:% S "% (Rece_data [. 1], rece_data [0] .decode ( " GBK " )))
 24  
25  
26 is  DEF main ():
 27      # Create a socket object 
28      UDP_SOCKET = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
 29      # bound port 
30      # Bing ((ip, port)) which is the bind a tuple, a first discharge ip can be empty, a second port 
31 is      udp_socket.bind (( '' , 7788 ))
 32      the while true:
 33 is          # Welcome menu 
34 is          available for purchase ()
 35          # select 
36          OP = INPUT ( "Enter the command you want to execute: " )
 37 [          IF OP == " . 1 " :
 38 is              # Send 
39              send_msg (UDP_SOCKET)
 40          elif OP == " 2 " :
 41 is              # receiving information 
42 is              recv_msg (UDP_SOCKET)
 43 is          elif OP = = " 0 " :
 44 is              BREAK 
45          the else :
 46 is              Print ( " choose the appropriate instruction: " )
 47      # closes the socket 
48     udp_socket.close()
49 
50 if __name__ == '__main__':
51     main()

 

Guess you like

Origin www.cnblogs.com/yifengs/p/11371975.html