2012-11-07 59 views
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 

回答

5

您需要使用适当的代码页将data中的字符串编码到缓冲区。例如:

data = input('> ') 
if not data: 
    break 
tcpCliSock.send(data.encode('utf-8')) 

服务器代码需要改变过:

response = '[%s] %s' % (ctime(), data.decode('utf-8')) 
tcpCliSock.send(response.encode('utf-8')) 

多见于:

How do I convert a string to a buffer in Python 3.1?

+0

这工作。但是当服务器试图发回数据时,我在服务器程序 '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

+0

您需要解码从套接字获得的内容,然后对您构建的新字符串进行编码。我会更新答案以反映这一点。 – kichik