Python: TypeError: str, bytes or bytearray expecte

2020-04-27 04:26发布

I'm trying to create a simple server to client based chat program and the issue is that when I try to execute c.sendto(data,client) this error appears saying that Client is an int but it's a tuple containing the port number and the address. I'm I supposed to convert the tuple to bytes so I can send the message to the clients?

Server Script

import socket

clients = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1",7999))
s.listen()
print("Waiting for connection")
c, addr = s.accept()


while True:
    data , addr = c.recvfrom(1024)
    print(data)
    if addr not in clients:
        clients.append(addr)
        print(clients[0])
    if data:
        for client in clients:
            print(client)
            c.sendto(data,client)
s.close()

Client Script

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
addr = ("127.0.0.1",7999)
s.connect(addr)    
while True:
    string = input(">>")
    s.send(string.encode("utf-8"))
    data =s.recv(1024)
s.close()

Server Output

1条回答
看我几分像从前
2楼-- · 2020-04-27 05:09

The problem is that you're using sendto() with a connection-mode socket. I think you want c.send(data) instead.

Details:

The Python docs for sendto say "The socket should not be connected to a remote socket, since the destination socket is specified by address." Also the man page for sendto says "If sendto() is used on a connection-mode (SOCK_STREAM, SOCK_SEQPACKET) socket, the arguments dest_addr and addrlen are ignored (and the error EISCONN may be returned when they are not NULL and 0)." I somewhat suspect that this is happening and Python is misreporting the error in a confusing way.

The sockets interface and networking in general can be pretty confusing but basically sendto() is reserved for SOCK_DGRAM which is UDP/IP type internet traffic, which you can think of as sending letters or postcards to a recipient. Each one goes out with a recipient address on it and there's no guarantee on order of receipt. On the other hand, connection-mode sockets like SOCK_STREAM use TCP/IP which is a bit more like a phone call in that you make a connection for a certain duration and and each thing you send is delivered in order at each end.

Since your code seems to be designed for communication over a connection I think you just want c.send(data) and not sendto.

查看更多
登录 后发表回答