Tidy up code and remove initial framework

This commit is contained in:
Kayomn 2021-09-30 01:25:55 +01:00
parent a46242999b
commit f6fede5872
2 changed files with 63 additions and 100 deletions

View File

@ -4,23 +4,32 @@ __status__ = "Development"
if (__name__ == "__main__"): if (__name__ == "__main__"):
import config import config
import socket as network import socket
import message import select
import sys
def init() -> None: address = (config.host, config.port)
address = (config.host, config.port)
print("Starting connection to", address) print("Starting connection to", address)
with network.socket(network.AF_INET, network.SOCK_STREAM) as socket: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
socket.setblocking(False) server_socket.setblocking(False)
socket.connect_ex(address) server_socket.connect_ex(address)
while True: inputs = [sys.stdin, server_socket]
message_body = input("Enter a message: ")
print("\n") while True:
socket.send(message.serialize("Kayomn", message_body)) readable_io, _, _ = select.select(inputs, [], [])
init() for io in readable_io:
if (io == server_socket):
print(io.recv(4096))
elif (io == sys.stdin):
message = sys.stdin.readline()
server_socket.send(message.encode("utf-8"))
sys.stdout.write("<You>")
sys.stdout.write(message)
sys.stdout.flush()

128
server.py
View File

@ -3,102 +3,56 @@ __version__ = "0.0.1"
__status__ = "Development" __status__ = "Development"
if (__name__ == "__main__"): if (__name__ == "__main__"):
import threading
import config import config
import traceback import socket
import socket as network
import selectors
import message
class User: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
def __init__(self, user_socket: network.socket): # Avoid bind() exception: OSError: [Errno 48] Address already in use
self.socket = user_socket client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.connection, self.address = user_socket.accept() client_socket.bind((config.host, config.port))
self.selector = selectors.DefaultSelector() client_socket.listen()
print("Accepted connection from", self.address) clients = []
self.connection.setblocking(False)
def close(self): def spawn_client(client_connection, client_address):
self.selector.close() client_connection.send("Welcome to this chatroom!".encode("utf-8"))
self.socket.close()
def read(self):
try:
# Should be ready to read
data = self.socket.recv(4096)
except BlockingIOError:
# Resource temporarily unavailable (errno EWOULDBLOCK)
pass
else:
if data:
print(message.deserialize(data))
else:
raise RuntimeError("Peer closed.")
def write(self):
pass
def run(self):
try:
while True:
events = self.selector.select(timeout=None)
for (key, mask) in events:
try:
if (mask & selectors.EVENT_READ):
self.read()
elif (mask & selectors.EVENT_WRITE):
self.write()
except Exception:
print(f"Exception raised on {self.address}: {traceback.format_exc()}"),
self.socket.close()
if not self.selector.get_map():
break
except KeyboardInterrupt:
print("caught keyboard interrupt, exiting")
finally:
self.selector.close()
def init():
address = (config.host, config.port)
selector = selectors.DefaultSelector()
with network.socket(network.AF_INET, network.SOCK_STREAM) as socket:
# Avoid bind() exception: OSError: [Errno 48] Address already in use
socket.setsockopt(network.SOL_SOCKET, network.SO_REUSEADDR, 1)
socket.bind(address)
socket.listen()
print("Listening on", address)
socket.setblocking(False)
selector.register(socket, selectors.EVENT_READ, data=None)
users = []
try: try:
while True: data = client_connection.recv(4096)
events = selector.select(timeout=None)
for (key, mask) in events: print("test", data if data else "OOOPS")
if key.data is None:
user = User(key.fileobj)
users.append(user) while data:
user.run() message = "<" + client_address[0] + "> " + data
except KeyboardInterrupt: print(message)
print("Caught keyboard interrupt, exiting")
finally: for client in clients:
for user in users: if client != client_connection:
user.close() try:
client.send(message)
selector.close() except:
client.close()
# if the link is broken, we remove the client
if client_connection in clients:
clients.remove(client_connection)
init() data = client_connection.recv(4096)
if client_connection in clients:
print("dead")
clients.remove(client_connection)
except:
return
while True:
connection, address = client_socket.accept()
clients.append(connection)
# prints the address of the user that just connected
print(address[0] + " connected")
threading.Thread(target=spawn_client, args=(connection, address)).start()