3

我正在尝试制作时间戳服务器和客户端。客户端代码为:

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 
4

1 回答 1

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'))

更多信息请访问:

如何在 Python 3.1 中将字符串转换为缓冲区?

于 2012-11-07T20:17:50.590 回答