TypeError - python中的客户端错误

时间:2015-09-15 15:13:40

标签: python python-3.x network-programming

我在python中创建了一个客户端/服务器代码。服务器运行良好,并在8000端口上侦听,但当我通过客户端连接到它然后我尝试向服务器发送消息时,我收到以下错误:

Traceback (most recent call last):
  File "C:\Users\milad\workspace\NetworkProgramming\client.py", line 26, in <module>
    if __name__ == "__main__" : main()
  File "C:\Users\milad\workspace\NetworkProgramming\client.py", line 20, in main
    TcpSocket.send(sendData)
TypeError: 'str' does not support the buffer interface

我不知道如何解决有关客户端代码的问题。在下面我把客户端代码。我用Python语言编写它。

#!/usr/bin/python3

import socket
from builtins import input

def main():
    serverHostNumber = input("Please enter the ip address of the server: \n")
    serverPortNumber = input("Please enter the port of the server: \n")

    # create a socket object
    TcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

    # connection to hostname on the port.
    TcpSocket.connect((serverHostNumber, int(serverPortNumber)))                                                                    

    while True:
        data = TcpSocket.recv(1024)
        print("Server : ", data)
        sendData = str(input("Client : "))
        TcpSocket.send(sendData)



    TcpSocket.close()

if __name__ == "__main__" : main()

2 个答案:

答案 0 :(得分:2)

    TcpSocket.send(sendData)

看起来send仅接受bytes个实例。尝试:

    TcpSocket.send(bytes(sendData, "ascii")) #... or whatever encoding is appropriate

答案 1 :(得分:0)

套接字类的python 2文档显示接受字符串参数的.send函数/方法 - 但是如果你查看python 3 documentation for the same class,你会看到.send现在需要将数据作为一个传递给bytearray类型的参数。

更改:

sendData = str(input("Client : "))

sendData = str.encode(input("Client : "))
我相信

应该做的。