Python Sockets Peer to Peer

user3566150 picture user3566150 · Apr 24, 2014 · Viewed 15.5k times · Source

I'm trying to make a simple Peer to Peer Network in Python 2.7. The problem is, I can't seem to be able to create a connection between two machines in which they both act as a server and a client. I can get it to work when one is a server and the other is a client but not when they are both, both. Do I need to create 2 sockets? Also I'm using TCP to connect.

UPDATE:

import socket, sys               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

if sys.argv[1] == "connect":
    host = sys.argv[2]
    s.connect((host, port))
    s.close 
else:
    s.listen(5)                 # Now wait for client connection.
    while True:
       c, addr = s.accept()     # Establish connection with client.
       print 'Got connection from', addr
       c.send('Thank you for connecting')
       c.close()

The codes not very good because for someone to connect as a client they have to use the argument "connect" followed by the hostname or IP of the second machine. I can't get the two to connect and serve to each other simultaneously.

Answer

Chase Adams picture Chase Adams · Apr 24, 2014

Yes, two sockets are necessary. The listening socket should open on a constant port, and the client port should be opened on a different (potentially dynamic) port, usually higher in the port range. As an example:

Server sockets on port 1500, client sockets on port 1501.

Peer1: 192.168.1.101

Peer2: 192.168.1.102

When peer1 connects to peer2 it looks like this: 192.168.1.101:1501 -> 192.168.1.102:1500.

When peer2 connects to peer1 it looks like this: 192.168.1.102:1501 -> 192.168.1.101:1500.

Listening TCP sockets are also generally run on a separate thread since they are blocking.