2021-09-30 01:21:18 +02:00
|
|
|
__author__ = "Kieran Osborne"
|
|
|
|
__version__ = "0.0.1"
|
|
|
|
__status__ = "Development"
|
|
|
|
|
|
|
|
if (__name__ == "__main__"):
|
2021-09-30 02:25:55 +02:00
|
|
|
import threading
|
2021-09-30 01:21:18 +02:00
|
|
|
import config
|
2021-09-30 02:25:55 +02:00
|
|
|
import socket
|
2021-09-30 01:21:18 +02:00
|
|
|
|
2021-09-30 02:25:55 +02:00
|
|
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
|
|
|
|
# Avoid bind() exception: OSError: [Errno 48] Address already in use
|
|
|
|
client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
|
|
client_socket.bind((config.host, config.port))
|
|
|
|
client_socket.listen()
|
2021-09-30 01:21:18 +02:00
|
|
|
|
2021-09-30 02:25:55 +02:00
|
|
|
clients = []
|
2021-09-30 01:21:18 +02:00
|
|
|
|
2021-09-30 02:25:55 +02:00
|
|
|
def spawn_client(client_connection, client_address):
|
|
|
|
client_connection.send("Welcome to this chatroom!".encode("utf-8"))
|
2021-09-30 01:21:18 +02:00
|
|
|
|
|
|
|
try:
|
2021-09-30 02:25:55 +02:00
|
|
|
data = client_connection.recv(4096)
|
2021-09-30 01:21:18 +02:00
|
|
|
|
2021-09-30 02:25:55 +02:00
|
|
|
print("test", data if data else "OOOPS")
|
2021-09-30 01:21:18 +02:00
|
|
|
|
2021-09-30 02:25:55 +02:00
|
|
|
while data:
|
|
|
|
message = "<" + client_address[0] + "> " + data
|
2021-09-30 01:21:18 +02:00
|
|
|
|
2021-09-30 02:25:55 +02:00
|
|
|
print(message)
|
2021-09-30 01:21:18 +02:00
|
|
|
|
2021-09-30 02:25:55 +02:00
|
|
|
for client in clients:
|
|
|
|
if client != client_connection:
|
|
|
|
try:
|
|
|
|
client.send(message)
|
2021-09-30 01:21:18 +02:00
|
|
|
|
2021-09-30 02:25:55 +02:00
|
|
|
except:
|
|
|
|
client.close()
|
|
|
|
# if the link is broken, we remove the client
|
|
|
|
if client_connection in clients:
|
|
|
|
clients.remove(client_connection)
|
2021-09-30 01:21:18 +02:00
|
|
|
|
2021-09-30 02:25:55 +02:00
|
|
|
data = client_connection.recv(4096)
|
2021-09-30 01:21:18 +02:00
|
|
|
|
2021-09-30 02:25:55 +02:00
|
|
|
if client_connection in clients:
|
|
|
|
print("dead")
|
|
|
|
clients.remove(client_connection)
|
2021-09-30 01:21:18 +02:00
|
|
|
|
2021-09-30 02:25:55 +02:00
|
|
|
except:
|
|
|
|
return
|
2021-09-30 01:21:18 +02:00
|
|
|
|
2021-09-30 02:25:55 +02:00
|
|
|
while True:
|
|
|
|
connection, address = client_socket.accept()
|
2021-09-30 01:21:18 +02:00
|
|
|
|
2021-09-30 02:25:55 +02:00
|
|
|
clients.append(connection)
|
2021-09-30 01:21:18 +02:00
|
|
|
|
2021-09-30 02:25:55 +02:00
|
|
|
# prints the address of the user that just connected
|
|
|
|
print(address[0] + " connected")
|
|
|
|
threading.Thread(target=spawn_client, args=(connection, address)).start()
|