python - TypeError - python 中的客户端错误

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

最佳答案

    TcpSocket.send(sendData)

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

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

关于python - TypeError - python 中的客户端错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32589653/

相关文章:

python - 子类化 float 以强制 python 中的定点打印精度

c - getsockopt() 中的 optlen 参数

c# - 集中式数据库 : multiple consumers

java - 无法使用在 Ubuntu 18.04/Windows 10 上运行的 WildFly 17 发送电子邮件

python - 有没有什么方法可以改变多类分类问题中目标类的数量?

python - Pandas + scikit-learn K-means 无法正常工作 - 将所有数据帧行视为一个大的多维示例

python-3.x - tensorflow 1.8 与 python 3.6 在 windows64

python - 如何在 Altair 中设置标签文本大小?

python - TfIdf 矩阵返回 BernoulliNB 的特征数量错误

python - 是否有任何支持 Windows 7 样式文件选择器的 python GUI 框架?