今日学习Python,学习书本叫《Python核心编程(第三版)》!
按照书本的代码编写,发现TCP和UDP的客户端都无法正确显示信息,根据错误提示,在网上搜集了原因,不敢独享,并在此备案
参考:https://stackoverflow.com/questions/13274553/python-3-3-socket-typeerror
原因是Python3.1之后的改动,
Python3 TCP时间戳服务器端代码
#!/usr/bin/env python
from socket import *
from time import ctime
HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)
tcpSerSock = socket(AF_INET,SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
print('waiting for connecting...')
tcpCliSock, addr = tcpSerSock.accept()
print('...connect from:',addr)
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
response = '[%s] %s' % (ctime(), data.decode('utf-8'))
tcpCliSock.send(response.encode('utf-8'))
tcpCliSock.close()
tcpSerSock.close()
Python3 TCP时间戳服客户端代码
#!/usr/bin/env python
from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)
tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
data = input('> ')
if not data:
break
tcpCliSock.send(data.encode('utf-8'))
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
print(data.decode('utf-8'))
tcpCliSock.close()
TCP服务器端运行图
TCP客户端运行图

Python3 UDP时间戳服务器端代码
#!/usr/bin/env python3
from socket import *
from time import ctime
HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)
udpSerSock = socket(AF_INET,SOCK_DGRAM)
udpSerSock.bind(ADDR)
while True:
print('waiting for message ...')
data,addr = udpSerSock.recvfrom(BUFSIZ)
response = '[%s] %s' % (ctime(), data.decode('utf-8'))
udpSerSock.sendto(response.encode('utf-8'),addr)
print('..received from and returned to:')
udpSerSock.close()
Python3 UDP时间戳服客户端代码
#!/usr/bin/env python3
from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)
udpCliSock = socket(AF_INET,SOCK_DGRAM)
while True:
data = input('> ')
if not data:
break
udpCliSock.sendto(data.encode('utf-8'),ADDR)
data,ADDR = udpCliSock.recvfrom(BUFSIZ)
if not data:
break
print(data.decode('utf-8'))
udpCliSock.close()
UDP服务器端运行图
UDP客户端运行图