问题
I created a Client/Server code in python. Server works well and get listen on 8000 port, but when I connect to it via client and then I try to send a message to server I get the following error:
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
I don't know how can I fix this problem about the client code. In the following I put the client code. I written it with Python language.
#!/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()
回答1:
TcpSocket.send(sendData)
Looks like send accepts only bytes
instances. Try:
TcpSocket.send(bytes(sendData, "ascii")) #... or whatever encoding is appropriate
回答2:
The python 2 documentation for the sockets class shows the .send function/method accepting a string parameter - but if you look at the python 3 documentation for the same class you'll see that .send now requires the data to be passed as a parameter of type bytearray.
Changing:
sendData = str(input("Client : "))
to
sendData = str.encode(input("Client : "))
should do the trick, I believe.
来源:https://stackoverflow.com/questions/32589653/typeerror-client-error-in-python