Laschet Jain
Laschet Jain

Reputation: 744

Can a socket listen and connect simultaneously

I want to design a P2P network. This is a simplified program that explains my problem.

I want to ask is there a way to connect and accept connection simultaneously.

If not, do P2P networks use two ports, one to accept and other to connect.

I am using thread because I have to run sample of this program in all machines. That's why I'm taking input of host and port. On main thread it accepts connection and other connect.

The program below give me the following error:

socket.error: [Errno 106] Transport endpoint is already connected

import socket
from threading import Thread

s = socket.socket()
s.bind(('localhost', 6000))

def rec():
    s.listen(1)
    c, addr = s.accept()
    print 'Connection received from ' , addr

def test():
    host = raw_input("Enter Host address : ")
    port = input("Enter port : ")
    s.connect((host, port))
    print s.getsockname()[0]

def main():
     t = Thread(target=rec, args=())
     t.start()
     test()

if __name__ == '__main__':
    main()

Upvotes: 3

Views: 3036

Answers (1)

tdelaney
tdelaney

Reputation: 77337

You can't listen and connect on the same socket. A listen socket can only be used to accept connections and a connection socket can only be a single bi-directional pipe. Further, if you try to do the same action such as send in multiple threads, you risk interleaving data. Your client should open its own socket, skip the bind and let the system assign the local connection port for you.

Since the created socket is bi-directional, a P2P app can communicate both ways and the choice of who does the connecting and who does the listening is based on other factors. You could, for instance, have both P2P machines listen so either side could start the conversation, but once its started, it runs on the bi-directional pipe.

zeromq is an interesting messaging system that can be used for P2P protocols. It has a very detailed description of various communication models and is well worth the read.

Upvotes: 3

Related Questions