书籍是《python核心编程》第三版,学习环境py3.6
2-1 时间戳服务器
附源代码:
1 from socket import * 2 from time import ctime 3 HOST='' 4 PORT=8888 5 BUFSIZ=1024 6 ADDR=(HOST,PORT) 7 tcpSerSock=socket(AF_INET,SOCK_STREAM) 8 tcpSerSock.bind(ADDR) 9 tcpSerSock.listen(5) 10 while True: 11 print("waiting for connection...") 12 tcpCliSock,addr=tcpSerSock.accept() 13 print('connected from:',addr) 14 while True: 15 data=tcpCliSock.recv(BUFSIZ).decode() 16 if not data: 17 break 18 tcpCliSock.send(("[%s]%s"%(ctime(),data))) 19 tcpCliSock.close() 20 tcpSerSock.close()
运行后
Traceback (most recent call last):
File "F:/learn_test/时间戳服务器.py", line 18, in <module>
tcpCliSock.send(("[%s]%s" % (ctime(), data)))
TypeError: a bytes-like object is required, not 'str'
提示需要一个bytes类型的对象,而不是str
。。。。照着书敲都会有错
这还能难住老夫?
1 from socket import * 2 from time import ctime 3 HOST='' 4 PORT=8888 5 BUFSIZ=1024 6 ADDR=(HOST,PORT) 7 tcpSerSock=socket(AF_INET,SOCK_STREAM) 8 tcpSerSock.bind(ADDR) 9 tcpSerSock.listen(5) 10 while True: 11 print("waiting for connection...") 12 tcpCliSock,addr=tcpSerSock.accept() 13 print('connected from:',addr) 14 while True: 15 data=tcpCliSock.recv(BUFSIZ).decode() 16 if not data: 17 break 18 tcpCliSock.send(("[%s]%s"%(ctime(),data)).encode()) 19 tcpCliSock.close() 20 tcpSerSock.close()
然后继续运行
Traceback (most recent call last):
File "F:/learn_test/时间戳服务器.py", line 15, in <module>
data=tcpCliSock.recv(BUFSIZ).decode()
OSError: [WinError 10038] 在一个非套接字上尝试了一个操作。
修正后
1 from socket import * 2 from time import ctime 3 HOST='' 4 PORT=8888 5 BUFSIZ=1024 6 ADDR=(HOST,PORT) 7 tcpSerSock=socket(AF_INET,SOCK_STREAM) 8 tcpSerSock.bind(ADDR) 9 tcpSerSock.listen(5) 10 while True: 11 print("waiting for connection...") 12 tcpCliSock,addr=tcpSerSock.accept() 13 print('connected from:',addr) 14 while True: 15 data=tcpCliSock.recv(BUFSIZ).decode() 16 if not data: 17 break 18 # tcpCliSock.send(("[%s]%s" % (ctime(), data))) 19 tcpCliSock.send(("[%s]%s"%(ctime(),data)).encode()) 20 tcpCliSock.close() 21 tcpSerSock.close()
区别就是描红的那一行
本次表演到此结束