DEV Community

Cover image for Client / Server Chat
Scott Gordon
Scott Gordon

Posted on

Client / Server Chat

Github Repo

Console Output

# client_server_chat
#   This is a program to demonstate a chat between client and server using UDP.
#   Run this program and add either client or server as an argument.
#   Once you have run both client and server you can chat between them.
# by Scott Gordon with help from

import argparse, socket

MAX_SIZE_BYTES = 65535  # Mazimum size of a UDP datagram

def server(port):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    hostname = ""
    s.bind((hostname, port))
    print("Listening at {}".format(s.getsockname()))
    while True:
        data, clientAddress = s.recvfrom(MAX_SIZE_BYTES)
        message = data.decode("ascii")
        print("The client at {} says {!r}".format(clientAddress, message))
        msg_to_send = input("Input message to send to client:")
        data = msg_to_send.encode("ascii")
        s.sendto(data, clientAddress)

def client(port):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    host = ""
    while True:
        s.connect((host, port))
        message = input("Input message to send to server:")
        data = message.encode("ascii")
        data = s.recv(MAX_SIZE_BYTES)
        text = data.decode("ascii")
        print("The server replied with {!r}".format(text))

if __name__ == "__main__":
    funcs = {"client": client, "server": server}
    parser = argparse.ArgumentParser(description="UDP client and server")
    parser.add_argument("functions", choices=funcs, help="client or server")
        "-p", metavar="PORT", type=int, default=3000, help="UDP port (default 3000)"
    args = parser.parse_args()
    function = funcs[args.functions]

Enter fullscreen mode Exit fullscreen mode

Verify my Python

Photo by Kelvin Ang on Unsplash

Discussion (0)