python- the udp socket programming

Use udp protocol

Server:

# ! / Usr / bin / python3 
# Coding: UTF-8 
# Auther: AlphaPanda 
# the Description: UDP server 
# Version: 1 
# a Date: Mon Dec 2 03:24:46 EST 2019 
# ## server 
Import socket
 # 1 Creating an object tpye = SOCK_DGRAM udp udp protocol on behalf of 
SK = socket.socket (of the type = socket.SOCK_DGRAM) 

# 2 binding Ip and port (register the host in the network, so that other servers can be found in the host) 
sk.bind (( " 127.0.0.1 " , 9000 )) 

# . 3 transmits and receives data logical 
" "" server udp, the first received data only "," " 
the while True: 
    MSG, cli_addr = sk.recvfrom (1024)
    print(msg.decode("utf-8"))
    message = input("server:>>>")
    if message == "q":
        break
    else:
        sk.sendto(message.encode("utf-8"),cli_addr)
# 4 关闭udp连接
sk.close()

Client:

# ! / Usr / bin / python3 
# Coding: UTF-8 
# Auther: AlphaPanda 
# the Description: udp client 
# Version 1 :: 
# a Date: Mon Dec 2 03:28:23 EST 2019 
"" " 
Import socket 
SK = socket .socket (type = socket.SOCK_DGRAM) 
sk.sendto ( "Hello" .encode ( "UTF-. 8"), ( "127.0.0.1", 9000)) 
MSG, dest_addr = sk.recvfrom (1024) 
Print (MSG. decode ( "UTF-. 8")) 
sk.close () 
"" " 
# import module 
import socket
 # generate a UDP type socket object 
SK = socket.socket (type = socket.
SOCK_DGRAM) # logic, data transmission and reception codes 
the while True: 
    Message= input("client:>>>")
    if message == "q":
        break
    else:
        sk.sendto(message.encode("utf-8"),("127.0.0.1",9000))
        msg,ser_addr = sk.recvfrom(1024)
        print(msg.decode("utf-8"))

# 关闭UDP连接    
sk.close()

 

Guess you like

Origin www.cnblogs.com/butterflies/p/11988749.html