Skip to content

Instantly share code, notes, and snippets.

@unworthyEnzyme
Last active April 26, 2024 08:55
Show Gist options
  • Save unworthyEnzyme/45f2df88bdd233b8e5a24b13a74415c0 to your computer and use it in GitHub Desktop.
Save unworthyEnzyme/45f2df88bdd233b8e5a24b13a74415c0 to your computer and use it in GitHub Desktop.
tcp broadcast
import socket
import sys
import threading
from message import Message
# Function to handle receiving messages from the server
def receive_messages(client_socket):
while True:
try:
# Receive message from the server
message = Message.decode(client_socket)
print("\n[Received]", message.contents)
except Exception as e:
print("Error:", e)
break
# Main function to start the client
def main():
# Define host and port to connect to
host = "localhost"
port = 3000
if len(sys.argv) > 1:
port = int(sys.argv[1])
# Create TCP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to the server
client_socket.connect((host, port))
print("Connected to server:", host, port)
# Start a new thread to receive messages from the server
receive_thread = threading.Thread(
target=receive_messages, args=(client_socket,)
)
receive_thread.start()
# Continuously send messages to the server
while True:
message = input()
if message.lower() == "exit":
break # Exit loop if user types 'exit'
# Send message to the server
client_socket.send(Message(message).encode())
except KeyboardInterrupt:
print("Client shutting down.")
finally:
# Close the socket
client_socket.close()
if __name__ == "__main__":
main()
from dataclasses import dataclass
@dataclass
class Message:
contents: str
def encode(self) -> bytes:
return f"{self.length:04d}".encode() + self.contents.encode()
@staticmethod
def decode(socket) -> "Message":
length = int(socket.recv(4).decode())
total_read = 0
contents = ""
while total_read < length:
read = socket.recv(1024).decode()
contents += read
total_read += len(read)
return Message(contents)
@property
def length(self) -> int:
return len(self.contents)
import socket
import sys
import threading
from message import Message
# Function to handle each client connection
def handle_client(client_socket, clients):
while True:
try:
# Receive message from the client
message = Message.decode(client_socket)
# Broadcast the message to all other clients
for c in clients:
if c != client_socket:
c.send(message.encode())
except Exception as e:
print("Error:", e)
break
# Remove the client from the list
clients.remove(client_socket)
client_socket.close()
# Main function to start the server
def main():
host = "0.0.0.0" # All available interfaces
port = 3000
if len(sys.argv) > 1:
port = int(sys.argv[1])
# Create TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the host and port
server_socket.bind((host, port))
# Listen for incoming connections (max 10 clients)
server_socket.listen(10)
print(f"Server listening on {host}:{port}")
# List to keep track of client sockets
clients = []
try:
while True:
# Accept incoming connection
client_socket, addr = server_socket.accept()
print("Client connected:", addr)
# Add client socket to the list
clients.append(client_socket)
# Start a new thread to handle the client
client_thread = threading.Thread(
target=handle_client, args=(client_socket, clients)
)
client_thread.start()
except KeyboardInterrupt:
print("Server shutting down.")
server_socket.close()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment