Skip to content

Instantly share code, notes, and snippets.

@TvoozMagnificent
Last active August 11, 2022 08:51
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/ff640ca278a4402d9f1bf6752c5ee7bb to your computer and use it in GitHub Desktop.
Save TvoozMagnificent/ff640ca278a4402d9f1bf6752c5ee7bb to your computer and use it in GitHub Desktop.
Client Side
import socket
import random
from threading import Thread
from datetime import datetime
from rich import print
import struct
# 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 = ": " # 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)
#def listen_for_messages(socket, callback):
# buff=""
# size=0
# while True:
# buff+=socket.read(1024)
# if len(buff)>=size + 4:
# if size>0:
# callback(buff[:size].decode('utf-8'))
# size,=struct.unpack("!L", buff[size:size+4])
# buff=buff[size+4:]
def listen_for_messages(socket=s, callback=print):
buff=b""
size=0
while True:
buff+=(socket.recv(1024))
if len(buff)>=size + 4:
if size>0:
callback(buff[:size].decode('utf-8'))
size,=struct.unpack("!L", buff[size:size+4])
buff=buff[size+4:]
print(size)
def listen_for_messages(socket=s, callback=print):
buff=b""
size=0
while True:
buff+=(socket.recv(1024))
if size == 0:
size,=struct.unpack("!L", buff[:4])
buff=buff[4:]
if len(buff)>=size:
callback(buff[:size].decode('utf-8'))
buff=buff[size:]
size=0
# 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
x=to_send.encode();s.send(struct.pack('!L', len(x))+x)#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