lab

mail@pastecode.io avatar
unknown
python
a month ago
3.9 kB
2
Indexable
Never
server
import socket
import sys


class Server:
    def __init__(self, dest, port):
        self.server_port = port
        self.server_addr = dest
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.bind((self.server_addr, self.server_port))
    def forward_message(self, msg, addr_port_tuple):
        forward_msg = "forward_message" + " " + msg
        self.sock.sendto(forward_msg.encode("utf-8"), addr_port_tuple)
    def start(self):
        users = {}
        while True:
            keys = list(users.keys())
            values = tuple(users.values())
            
            client_message, client_addr_port = self.sock.recvfrom(4096)
            client_message = client_message.decode("utf-8")
            datalist = client_message.split()
            if datalist[0] == "join":
                users.update({datalist[1] : client_addr_port})
                print(datalist[1], "joined the chatroom")
            elif datalist[0] == "send_message":
                sender_client = keys[values.index(client_addr_port)]
                client = datalist[1]
                print("msg from:", sender_client, "msg to:", client)
                actual_message = " ".join(datalist[2:])
                actual_message = sender_client + ": " + actual_message
                self.forward_message(actual_message, values[keys.index(client)])
if __name__ == "__main__":
    PORT = 11000
    DEST = "localhost"
    print("Server started. Address:", DEST, "Port:", PORT)
    SERVER = Server(DEST, PORT)
    try:
        SERVER.start()  
    except (KeyboardInterrupt, SystemExit):
        exit()



client

import socket
import sys
import random
from threading import Thread
import getopt

class Client:

    def __init__(self, username, dest, port):
        self.server_addr = dest
        self.server_port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.bind(("", random.randint(10000, 40000)))
        self.name = username
    def join(self):
        join_message = "join" + " " + self.name
        self.sock.sendto(join_message.encode("utf-8"),(self.server_addr,self.server_port))
    def send_message(self, msg):
        actual_message = "send_message" + " " + msg
        self.sock.sendto(actual_message.encode("utf-8"),(self.server_addr,self.server_port))
    def start(self):
        self.join()
        while True:
            userinput = input()
            input_recv = userinput.split()
            if input_recv[0] == "msg":
                self.send_message(" ".join(input_recv[1:]))
            else:
                print("incorrect userinput format")
                continue
    def receive_handler(self):
        while True:
            server_message, server_addr_port = self.sock.recvfrom(4096)
            server_message = server_message.decode("utf-8")
            datalist = server_message.split()
            if datalist[0] == "forward_message":
                msg_recv_list = datalist[1:]
                msg_recv = " ".join(msg_recv_list)
                print(msg_recv)
if __name__ == "__main__":
    DEST = 'localhost'
    PORT = 11000
    try:
        OPTS, ARGS = getopt.getopt(sys.argv[1:], "u:", ["user="])
    except:
        print("Wrong command entered.")
        exit(1)
        
    USER_NAME = None
    for o, a in OPTS:
        if o in ("-u", "--user="):
            USER_NAME = a
    if USER_NAME is None:
        print("Missing Username.")
        exit(1)
    S = Client(USER_NAME, DEST, PORT)
    try:
        # Start receiving Messages
        T = Thread(target=S.receive_handler)
        T.daemon = True
        T.start()
        # Start Client
        S.start()
    except (KeyboardInterrupt, SystemExit):
        sys.exit()
Leave a Comment