python 3 tcp服务器和客户端字符串传输错误

时间:2017-01-14 21:49:54

标签: python-3.x sockets tcp tcpclient tcpserver

我尝试开发一个简单的服务器和客户端程序,我使用python 3.4.2运行代码。(在Debian 8.6上)。服务器运行良好,客户端程序连接到服务器但是当我在终端传递文本发送到服务器并发回时间戳时,我在客户端终端窗口中收到此错误

  

追踪(最近一次通话):     文件“tcp_client”,第15行,in       tcpCliSock.send(数据)   TypeError:'str'不支持缓冲区接口

这是服务器代码

from socket import *
from time import ctime

HOST = '192.168.0.141'
PORT = 21577
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()

这就是客户端代码

from socket import *

HOST = '192.168.0.141'
PORT = 21577
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()

0 个答案:

没有答案