Error: Transport endpoint is not connected (Python Sockets)

10,858

You're using server sockets incorrectly. You cannot recv on server sockets, instead you accept connections on them; accept returns the actual connection socket:

ser_sock.listen(1)
sock, addr = ser_sock.accept()

print('Got connection from {}'.format(addr))

# only this *connection* socket can receive!
data = sock.recv(4096)
Share:
10,858
Atinesh
Author by

Atinesh

THINK ACT BECOME

Updated on June 16, 2022

Comments

  • Atinesh
    Atinesh almost 2 years

    I'm trying to create a simple chat application using sockets in Python (with threads). Application is simple client has to threads one to send data and another to receive. Server has to two threads one to accept client connection and another to broadcast the message. But on running the below code, I'm getting error message

    Transport endpoint is not connected

    enter image description here

    Can anybody tell me why I'm getting this error

    Client

    import socket, threading
    
    def send():
        msg = raw_input('Me > ')
        cli_sock.send(msg)
    
    def receive():
        data = cli_sock.recv(4096)
        print('> '+ str(data))
    
    if __name__ == "__main__":   
        # socket
        cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
        # connect
        HOST = 'localhost'
        PORT = 5028
        cli_sock.connect((HOST, PORT))     
        print('Connected to remote host...')
    
        thread_send = threading.Thread(target = send)
        thread_send.start()
    
        thread_receive = threading.Thread(target = receive)
        thread_receive.start()
    

    Server

    import socket, threading
    
    def accept_client():
        while True:
            #accept    
            cli_sock, cli_add = ser_sock.accept()
            CONNECTION_LIST.append(cli_sock)
            print('Client (%s, %s) connected' % cli_add)
    
    def broadcast_data():
        while True:
            data = ser_sock.recv(4096)
            for csock in CONNECTION_LIST:
                try:
                    csock.send(data)
                except Exception as x:
                    print(x.message)
                    cli_sock.close()
                    CONNECTION_LIST.remove(cli_sock)
    
    if __name__ == "__main__":    
        CONNECTION_LIST = []
    
        # socket
        ser_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
        # bind
        HOST = 'localhost'
        PORT = 5028
        ser_sock.bind((HOST, PORT))
    
        # listen        
        ser_sock.listen(1)
        print('Chat server started on port : ' + str(PORT))
    
        thread_ac = threading.Thread(target = accept_client)
        thread_ac.start()
    
        thread_bd = threading.Thread(target = broadcast_data)
        thread_bd.start()