简体   繁体   中英

Python: TypeError: str, bytes or bytearray expected, not int

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

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.

You must first convert the string that contains the IP address into a byte or a string of bytes and then start communicating. According to the code below, your error will be resolved. Make sure your code is working correctly overall.

string = '192.168.1.102'
new_string = bytearray(string,"ascii")
ip_receiver = new_string
s.sendto(text.encode(), (ip_receiver, 5252))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM