I was playing with python socket programming to understand them better and decided to use p2p communication. But there is a problem that I face.
You see I have two codes: peer1 and peer2. Both are quite straightforward and easy.
Peer1:
import socket
import time
from tqdm import tqdm
HOST = '127.0.0.1'
PORT_S = 9090
PORT_R = 8080
client_skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv_skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv_skt.bind((HOST, PORT_R))
serv_skt.listen(1)
for i in tqdm(range(5), desc = 'You have 5 seconds to run the other peer program...'):
time.sleep(1)
client_skt.connect((HOST,PORT_S))
# msg=client_skt.recv(1024)
# msg=msg.decode('utf-8')
# print(msg)
print("waiting for a friend...")
connection, address = serv_skt.accept()
welcome_message = "Welcome to " + HOST + " at " + str(PORT_R)
welcome_message = welcome_message.encode('utf-8')
connection.send(welcome_message)
print("Connection successful: connected to ", address)
while True:
msg=input("Enter your message: \n")
msg=msg.encode("utf-8")
client_skt.sendall(msg)
data = connection.recv(1024).decode('utf-8')
if not data: break
print("Recieved: ", data)
Exactly same for peer2 but with the ports interchanged:
Peer2:
import socket
import time
from tqdm import tqdm
HOST = '127.0.0.1'
PORT_R = 9090
PORT_S = 8080
serv_skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv_skt.bind((HOST, PORT_R))
serv_skt.listen(1)
for i in tqdm(range(5), desc = 'You have 5 seconds to run the other peer program...'):
time.sleep(1)
client_skt.connect((HOST,PORT_S))
# msg=client_skt.recv(1024)
# msg=msg.decode('utf-8')
# print(msg)
print("waiting for a client...")
connection, address = serv_skt.accept()
welcome_message = "Welcome to " + HOST + " at " + str(PORT_R)
welcome_message = welcome_message.encode('utf-8')
connection.send(welcome_message)
print("Connection successful: connected to ", address)
while True:
data = connection.recv(1024).decode('utf-8')
if not data: break
print("Recieved: ", data)
msg=input("Enter your message: \n")
msg=msg.encode("utf-8")
client_skt.sendall(msg)
connection.close()
Most of you might have already guessed it: I can't run a client and a server at the same time, which throws me an error.
One way to counter this is to just sleep until the server binds. It works but it doesn't exit gracefully.
Q. Is there any alternate approach to this? Can one achieve p2p using sockets other than the approach mentioned above?