socket 创建UDP服务器和客户端

 

服务器端代码:

from socket import *
from time import ctime

HOST = ''
PORT = 1234
ADDR = (HOST, PORT)
BUFSIZE = 1024

def main():
udpSer = socket(AF_INET, SOCK_DGRAM)
udpSer.bind(ADDR)
while True:
print('waiting for message...')
data, adr = udpSer.recvfrom(BUFSIZE) #通过函数recvfrom返回元祖(消息,地址)
data = '[%s]%s' % (ctime(), data.decode('UTF-8'))
udpSer.sendto(bytes(data, 'UTF-8'), adr) #通过函数sento发送消息到adr地址
print('...received from and returned to:', adr)

udpSer.close()

main()

客户端代码:

from socket import *
from time import ctime

HOST = 'LOCALHOST'
PORT = 1234
ADDR = (HOST, PORT)
BUFSIZE = 1024

def main():
udpCli = socket(AF_INET, SOCK_DGRAM)
while True:
data = input('>')
if not data:
break;
udpCli.sendto(bytes(data, 'UTF-8'), ADDR)
data, addr= udpCli.recvfrom(BUFSIZE)
data = data.decode('UTF-8')
if not data:
break;
print (data)
udpCli.close()

main()




posted @ 2012-03-22 21:39  icamel  阅读(497)  评论(0编辑  收藏  举报