Python Socket Encoding Error?
Hi, jedesmal wenn ich versuche mit dem Client eine Nachricht zu senden stürzt mir der Server ab. 

import socket
import threading


class TxtSocket:
    
    def __init__(self, host=socket.gethostbyname(socket.gethostname()) , port=5555, connection = 0, disconnect="!DISCONNECT"):
        self.host = host
        self.port = port
        self.connection = connection
        self.disconnect = disconnect
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.bind((self.host, self.port))
        print("Socket was created")


    def handle(self, conn, addr):
        while True:
            connection = threading.active_count() -1
            print(f"Connections: {connection}")
            data = conn.recv(1024).decode("utf8")
            if data == self.disconnect:
                conn.close()


            elif not data:
                break
            addr = str(addr[0])
            addr.encode()
            data.encode()
            print(type(data))
            print(type(addr))
            print(f"{addr}: {data}")
            self.s.send(addr[0], data)
        


    def server(self):
        self.s.listen(26)
        print("Server is listening")
        while True:
            conn, addr = self.s.accept()
            print(f"{addr} is now connected.")
            t = threading.Thread(target=self.handle, args=(conn, addr))
            t.start()
        


if __name__ == "__main__":
    txtsocket = TxtSocket()
    txtsocket.server()
 


#Client      
import socket


def Text():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((socket.gethostbyname(socket.gethostname()), 5555))
    print("Connected")
    while True:
        message = input("Deine Nachricht: ")
        message = message.encode("utf8")
        s.send(message)
Text()

ERROR:

Socket was created

Server is listening

('10.0.0.11', 55353) is now connected.

Connections: 1

<class 'str'>

<class 'str'>

10.0.0.11: s

Exception in thread Thread-1:

Traceback (most recent call last):

 File "C:\Users\Tobias\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner

  self.run()

 File "C:\Users\Tobias\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run

  self._target(*self._args, **self._kwargs)

 File "C:\Users\Tobias\OneDrive\Python\Server.py", line 30, in handle

  self.s.send(addr[0], data)

TypeError: a bytes-like object is required, not 'str'

Computer, programmieren, Informatik, Python

Meistgelesene Beiträge zum Thema Python