Allow for both Windows and Linux to use the same 'client'

This commit is contained in:
Charles Descamps 2025-03-19 18:38:20 -07:00
parent f3c913c97c
commit aad3ecd804

View file

@ -1,6 +1,7 @@
import socket import socket
import sys import sys
import select import select
import os
BUFFER_SIZE = 1024 BUFFER_SIZE = 1024
DEFAULT_HOST = 'localhost' DEFAULT_HOST = 'localhost'
@ -22,6 +23,29 @@ def main():
client_socket.connect((SERVER_HOST, SERVER_PORT)) client_socket.connect((SERVER_HOST, SERVER_PORT))
print(f"Connected to chat server at {SERVER_HOST}:{SERVER_PORT}") print(f"Connected to chat server at {SERVER_HOST}:{SERVER_PORT}")
if os.name == 'nt': # Windows-specific logic
import msvcrt
client_socket.setblocking(False) # Set the socket to non-blocking mode
while True:
# Check for server messages
try:
server_message = client_socket.recv(BUFFER_SIZE).decode('utf-8')
if server_message:
print(f"\n{server_message}")
print("> ", end="", flush=True)
except BlockingIOError:
pass
# Check for user input
if msvcrt.kbhit():
client_message = input("> ")
if client_message.strip() == "%!":
print("Exiting chat...")
break
client_socket.send(client_message.encode('utf-8'))
else: # Linux/Unix-specific logic
while True: while True:
# use select to wait for either server messages or user input # use select to wait for either server messages or user input
read_sockets, _, _ = select.select([client_socket, sys.stdin], [], []) read_sockets, _, _ = select.select([client_socket, sys.stdin], [], [])
@ -41,8 +65,6 @@ def main():
if client_message.strip() == "%!": if client_message.strip() == "%!":
print("Exiting chat...") print("Exiting chat...")
return return
# send message to server
client_socket.send(client_message.encode('utf-8')) client_socket.send(client_message.encode('utf-8'))
except Exception as e: except Exception as e: