Skip to content

Instantly share code, notes, and snippets.

@Compro-Prasad
Last active December 10, 2018 11:21
Show Gist options
  • Save Compro-Prasad/596412299ea56d1434ecdc2b7d8433aa to your computer and use it in GitHub Desktop.
Save Compro-Prasad/596412299ea56d1434ecdc2b7d8433aa to your computer and use it in GitHub Desktop.
P2P client
#!/usr/bin/python3
import socket
import threading
from time import sleep
max_peers = 4
port = 3333
thread_list = []
sock_list = {}
def make_server_socket(port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('0.0.0.0', port))
s.listen(5)
return s
def client_recieve_data(sock):
data = "null".encode()
while data.decode() != '':
data = sock.recv(32767)
print("\r" + data.decode() + "\nyou: ", end="")
sock.close()
def broadcast(server_socket, sender_ip, message):
global sock_list
for ip, sock in sock_list.items():
if ip != sender_ip:
msg = sender_ip + "> " + message.decode()
sock.send(msg.encode())
def server_read_input(sock):
data = "null"
while data != "exit" and data != "":
data = input("you: ")
broadcast(sock, "server", data.encode())
sock.close()
def handle_client(serv_sock, client_socket, client_ip):
global max_peers
global sock_list
x = "null".encode()
while x.decode() != '':
x = client_socket.recv(32767)
broadcast(serv_sock, client_ip, x)
print("\r" + client_ip + "> " + x.decode() + "\nyou: ", end="")
client_socket.close()
sock_list.pop(client_ip, 0)
max_peers += 1
def run_server():
global thread_list
global max_peers
global port
sock = make_server_socket(port)
thread = threading.Thread(target=server_read_input, args=[sock])
thread_list += [thread]
thread.start()
while True:
socket, address = sock.accept()
ip, port = address
ip = ip + ":" + str(port)
sock_list[ip] = socket
print("\rConnected to: " + ip + "\nyou: ", end="")
thread = threading.Thread(target=handle_client, args=[sock, socket, ip])
thread_list += [thread]
thread.start()
max_peers -= 1
while max_peers == 0:
sleep(2)
print("Waiting for other threads")
for t in thread_list:
t.join()
def run_client():
ip = input("Enter IP: ")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, port))
print('Connected to server')
thread = threading.Thread(target=client_recieve_data, args=[sock])
thread.start()
data = "null"
while data != "exit" and data != "":
data = input("you: ")
sock.send(data.encode())
thread.join()
sock.close()
try:
start = ""
while start != "s" and start != "c":
start = input("(S)tart/(C)onnect server? ").lower()[0]
if start == 's':
run_server()
else:
run_client()
except socket.error as msg:
print('Bind failed. Error Code : ' + str(msg) + ' Message ')
run_client()
except KeyboardInterrupt:
exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment