Skip to content

Instantly share code, notes, and snippets.

@TvoozMagnificent
Last active August 11, 2022 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TvoozMagnificent/cc7deec223eecf85fc17b84686dfd84a to your computer and use it in GitHub Desktop.
Save TvoozMagnificent/cc7deec223eecf85fc17b84686dfd84a to your computer and use it in GitHub Desktop.
My Chatting Server
import socket
import random
from threading import Thread
from datetime import datetime
try: from rich import print
except:
import os
os.system('pip install rich')
from rich import print
# from bot import bot
name = input("Enter your name >>> ")
if ":" in name: name=name.replace(":","")
name=name+str(random.randint(1000,10000))
# choose a random color for the client
# server's IP address
# if the server is not on this machine,
# put the private (network) IP address (e.g 192.168.1.2)
SERVER_HOST = "192.168.0.9"
SERVER_PORT = 5002 # server's port
separator_token = "<SEP>" # we will use this to separate the client name & message
# name = input("Enter your name: ")
# initialize TCP socket
s = socket.socket()
print(f"[*] Connecting to {SERVER_HOST}:{SERVER_PORT}...")
# connect to the server
s.connect((SERVER_HOST, SERVER_PORT))
print("[+] Connected. Simply type and press enter to send a message.")
# prompt the client for a name
# name = input("Enter your name: ")
def listen_for_messages():
while True:
message = s.recv(1024).decode()
print(message)
# bot(message)
# make a thread that listens for messages to this client & print them
t = Thread(target=listen_for_messages)
# make the thread daemon so it ends whenever the main thread ends
t.daemon = True
# start the thread
t.start()
while True:
# input message we want to send to the server
to_send = input()
# to_send = bot()
# a way to exit the program
if to_send.lower() == 'quit':
break
# add the datetime, name & the color of the sender
date_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
to_send = f"{name}{separator_token}{to_send}"
# finally, send the message
s.send(to_send.encode())
# close the socket
s.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment