【问题标题】:TypeError - Client error in pythonTypeError - python 中的客户端错误
【发布时间】:2015-09-15 15:13:40
【问题描述】:

我在 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()

【问题讨论】:

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


    【解决方案1】:
        TcpSocket.send(sendData)
    

    看起来 send 只接受 bytes 实例。试试:

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

    【讨论】:

      【解决方案2】:

      sockets 类的 python 2 文档显示 .send 函数/方法接受字符串参数 - 但如果您查看 python 3 documentation for the same class 您会看到 .send 现在需要将数据作为参数传递输入字节数组。

      变化:

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

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

      我相信应该可以解决问题。

      【讨论】:

        猜你喜欢
        • 2013-01-19
        • 2016-07-18
        • 2013-08-26
        • 2021-11-10
        • 1970-01-01
        • 1970-01-01
        • 2022-11-07
        • 2012-12-01
        • 1970-01-01
        相关资源
        最近更新 更多