昨天模拟书本上client和server交互的例子,代码明明是按照书上写的,可是就是出现了错误,像下面这样:
# tcpserver from socket import * from time import ctime HOST ='' PORT = 6555 BUFSIZ = 2048 ADDR = (HOST,PORT) tcpservsock = socket(AF_INET,SOCK_STREAM) tcpservsock.bind(ADDR) tcpservsock.listen(5) while True: print('waiting for connection...') tcpClisock,addr = tcpservsock.accept() print('...connected from:',addr) while True: data = tcpClisock.recv(BUFSIZ) if not data: break print(data.decode('utf8')) tcpClisock.send('[%s]%s'%(bytes(ctime(),'utf8'),data)) # 这里弹出错误 tcpClisock.close() tcpservsock.close()
#tcpClient from socket import * HOST = 'localhost' PORT = 6555 BUFSIZ = 2048 ADDR = (HOST,PORT) tcpClisock = socket(AF_INET,SOCK_STREAM) tcpClisock.connect(ADDR) while True: data = input('> ') if not data: break tcpClisock.send(data.encode()) data = tcpClisock.recv(BUFSIZ) if not data: break print(data.decode('utf-8')) tcpClisock.close()
然后错误就出现了:
waiting for connection... ...connected from: ('127.0.0.1', 3786) hi Traceback (most recent call last): File "C:\Users\yfg\Desktop\server.py", line 26, in <module> tcpClisock.send('[%s]%s'%(bytes(ctime(),'utf8'),data)) TypeError: a bytes-like object is required, not 'str'
在苦思冥想之后,我发现:在server.py line26中 ,我将二进制数据放在了 字符串格式化符后面,这是不对的,所以只要在原来 '[%s]%s'%(bytes(ctime(),'utf8'),data) 前面 加上 b ,就像这样 b'[%s]%s'%(bytes(ctime(),'utf8'),data) ,然后 跑起来 :在服务器这边得到这个 :
,在客户端这边得到这个: 问题就解决了 。 总结一下就是:字符串格式化后跟字符串,二进制格式化要在字符串格式前加字母b。