按照《Python核心编程》中实例进行练习,运行中发现报错,后根据网上资料修改后可以运行。
修正后代码:
服务器端:
from socket import *
from time import ctime
HOST =''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST,PORT)
udpSerSock = socket(AF_INET,SOCK_DGRAM)
udpSerSock.bind(ADDR)
while True:
print ('等待连接。。。')
data, addr = udpSerSock.recvfrom(BUFSIZE)
udpSerSock.sendto(('[%s] %s' %(ctime(), data.decode())).encode(), addr)
print('接收到请求来自%s的数据%s:'%(addr,data))
udpSerSock.close()
客户端:
from socket import *
HOST ='localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST,PORT)
udpCliSock = socket(AF_INET,SOCK_DGRAM)
while True:
data = input('>')
if not data:
break
udpCliSock.sendto((data).encode(),ADDR)
data,ADDR = udpCliSock.recvfrom(BUFSIZE)
if not data:
break
print(data.strip())
udpCliSock.close()