python 3.3 socket TypeError

时间:2012-11-07 17:03:00

标签: python sockets python-3.x 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 

1 个答案:

答案 0 :(得分: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?