3
我想製作一個時間戳服務器和客戶端。客戶端代碼是:蟒蛇3.3套接字TypeError
from socket import *
HOST = '127.0.0.1' # or '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)
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
print(data.decode('utf-8'))
tcpCliSock.close()
和服務器的代碼是:
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 connection...')
tcpCliSock, addr = tcpSerSock.accept()
print('connected from: ', addr)
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
tcpCliSock.send('[%s] %s' % (bytes(ctime(), 'utf-8'), data))
tcpCliSock.close()
tcpSerSock.close()
服務器工作正常,但是當我發送任何數據從客戶端我收到以下錯誤服務器:
File "tsTclnt.py", line 20, in <module>
tcpCliSock.send(data)
TypeError: 'str' does not support the buffer interface
這工作。但是當服務器試圖發回數據時,我在服務器程序 'tcpCliSock.send('[%s]%s'%(bytes(ctime(),'utf-8'),data)) TypeError:'str'不支持緩衝接口' 因此我將發送改爲 'tcpCliSock.send('[%s]%s'%(bytes(ctime(),'utf-8'),data .encode('utf-8')))' 哪給了我這個錯誤 'tcpCliSock.send('[%s]%s'%(bytes(ctime(),'utf-8'),data.encode ('utf-8'))) AttributeError:'bytes'對象沒有'encode''屬性 – khateeb
您需要解碼從套接字獲得的內容,然後對您構建的新字符串進行編碼。我會更新答案以反映這一點。 – kichik