python 3.3套接字类型错误

标签 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 

最佳答案

您需要使用适当的代码页将 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?

关于python 3.3套接字类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13274553/

相关文章:

c - getpeername函数的理解

python - QTcpSocket 和 python 套接字之间交换数据的正确方法是什么?

java - 服务器套接字读取长字符串

python - 使用 TLS1.1 和 urllib3 的 HTTP GET 站点

python - 如何在 CentOS 上将 Python3.5.2 设置为默认 Python 版本?

python - 有没有更好的方法来解析Python字典?

python - 从查询集中获取查询集

python - 具有颜色渐变的 Matplotlib 3D 散点图

php - 如何确保代码在重构后仍然有效(动态语言)

python - 如何创建一个小的 python 代码来获取团队通话的参与者列表?