Client Chat

Client Chat

June 07, 2023

 import socket

import random

from threading import Thread

from datetime import datetime

from colorama import Fore, init, Back

init()

colors = [Fore.BLUE, Fore.CYAN, Fore.GREEN, Fore.LIGHTBLACK_EX,

         Fore.LIGHTBLUE_EX, Fore.LIGHTCYAN_EX, Fore.LIGHTGREEN_EX,

         Fore.LIGHTMAGENTA_EX, Fore.LIGHTRED_EX, Fore.LIGHTWHITE_EX,

         Fore.LIGHTYELLOW_EX, Fore.MAGENTA, Fore.RED, Fore.WHITE, Fore.YELLOW]

client_color = random.choice(colors)

SERVER_IP = "127.0.0.1"

SERVER_PORT = 5002

seprator_token = "<SEP>"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print(f"[*] Connecting to {SERVER_IP}:{SERVER_PORT}...")

s.connect((SERVER_IP, SERVER_PORT))

print("[+] Connected.")

name = input("Masukkan Nama Anda: ")

def listen_for_messages():

        while True:

                message = s.recv(1024).decode()

                print("\n" + message)

t = Thread(target=listen_for_messages)

t.daemon = True

t.start()

while True:

        to_send = input()

        if to_send.lower() == 'q':

                break

        date_now = datetime.now().strftime('%Y-%d %H:%M:%S')

        to_send = f"{client_color}[{date_now}] {name}{seprator_token}{to_send}{Fore.RESET}"

        s.send(to_send.encode())

s.close()


Server Chat

Server Chat

June 07, 2023

 import socket

from threading import Thread

SERVER_IP       = "127.0.0.1"

SERVER_PORT     = 5002

separator_token = "<SEP>"

client_sockets  = set()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

s.bind((SERVER_IP, SERVER_PORT))

s.listen(5)

print(f"[*] Listening as {SERVER_IP}:{SERVER_PORT}")

def listen_for_client(cs):

    while True:

        try:

                msg = cs.recv(1024).decode()

        except Exception as e:

                print(f"[!] Error: {e}")

                client_socket.remove(cs)

        else:

                msg = msg.replace(separator_token, ": ")

        for client_socket in client_sockets:

                client_socket.send(msg.encode())

while True:

        client_socket, client_address = s.accept()

        print(f"[+] {client_address} connected.")

        client_sockets.add(client_socket)

        t = Thread(target=listen_for_client, args=(client_socket,))

        t.daemon = True

        t.start()

for cs in client_sockets:

        cs.close()

        s.close