Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python 3.3套接字类型错误_Python_Sockets_Python 3.x_Typeerror - Fatal编程技术网

python 3.3套接字类型错误

python 3.3套接字类型错误,python,sockets,python-3.x,typeerror,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

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

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 
文件“tsTclnt.py”,第20行,在
tcpCliSock.send(数据)
TypeError:“str”不支持缓冲区接口

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

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'))
更多信息,请访问:


这很有效。但是当服务器试图发回数据时,我在服务器程序
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”
您需要解码从套接字获得的内容,然后对生成的新字符串进行编码。我将更新答案以反映这一点。