from socket import *
from time import ctime
BUFFSIZE = 1024
HOST = "127.0.0.1"
PORT = 10055
ADDR = (HOST, PORT)
mySocket = socket(AF_INET, SOCK_DGRAM, 0)
mySocket.bind(ADDR)
while True:
print("waiting for message...\n")
data, addr = mySocket.recvfrom(BUFFSIZE)
data = data.decode()
print("connection from ", data)
if not data:
break
mySocket.sendto(("[%s] %s" % (ctime(), data)).encode(), addr)
mySocket.close()
UDPSocketClient:
from socket import *
BUFFSIZE = 1024
HOST = "127.0.0.1"
PORT = 10055
ADDR = (HOST, PORT)
mySocket = socket(AF_INET, SOCK_DGRAM,0)
while True:
data = input(">: ")
if not data:
break
mySocket.sendto(data.encode(), ADDR)
data, addr = mySocket.recvfrom(BUFFSIZE)
if not data:
break
print(data)
mySocket.close()
原文:http://blog.51cto.com/superhakce/2093206