Add new file

main
Justuser 2 years ago
parent 8cdc113fa3
commit 4dd7dec5cc

@ -0,0 +1,113 @@
import socket #send/recive packets
import threading #threads
from time import sleep #wait
from random import randint #gen username + random int
##############SETTINGS##################
global host, port
#YOUR/SERVER IP
host = "127.0.0.1"
#YOUR/SERVER PORT
port = 7015
##############SERVER##################
def server_listen(conn_temp):
global conn
while True:
#Recive data and check for empty data
data = conn_temp.recv(1024).decode()
if data:
print(str(data))
#Send to others clients data from user
for i in range(len(conn)):
if conn[i] == conn_temp:
continue
conn[i].send(data.encode())
def server_accept(s):
global conn, adress
while True:
#Listen socket ip:port and accept connection
s.listen(2) ; conn_temp, address = s.accept()
conn.append(conn_temp)
#If accepted start listen
th = threading.Thread(target=server_listen, args=(conn_temp,), daemon=True)
th.start()
#Send to all message about new user ( exclude user )
data = f"New connection from {str(address[1])}"
print(data)
for i in range(len(conn)):
if conn[i] == conn_temp:
continue
conn[i].send(data.encode())
def server():
global host, port
global conn, adress
conn = []
#Bind server socket
s = socket.socket() ; s.bind((host, port))
#Start accept-connections func
th = threading.Thread(target=server_accept, args=(s,), daemon=True)
th.start()
#Chat with clients
while True:
data = "Server > " + input('')
for i in range(len(conn)):
conn[i].send(data.encode())
s.close()
##############CLIENT##################
def client_listen(s):
global host, port
while True:
#Recive and print data
sleep(0.01)
data = s.recv(1024).decode()
if data:
print(data)
def client():
global host, port
#Bind client socket
s = socket.socket() ; s.connect((host, port))
#Start listen server
th = threading.Thread(target=client_listen, args=(s,), daemon=True)
th.start()
#Gen id and start chatting
id = str(randint(100,1000))
while True:
message = f"User{id} > " + input('')
s.send(message.encode())
s.close()
##############START##################
try:
client()
except:
server()
#If no server (can't connect to server - error), then start server or start client.
Loading…
Cancel
Save