Allow for both Windows and Linux to use the same 'client'
This commit is contained in:
parent
f3c913c97c
commit
aad3ecd804
1 changed files with 41 additions and 19 deletions
|
|
@ -1,6 +1,7 @@
|
|||
import socket
|
||||
import sys
|
||||
import select
|
||||
import os
|
||||
|
||||
BUFFER_SIZE = 1024
|
||||
DEFAULT_HOST = 'localhost'
|
||||
|
|
@ -22,29 +23,50 @@ def main():
|
|||
client_socket.connect((SERVER_HOST, SERVER_PORT))
|
||||
print(f"Connected to chat server at {SERVER_HOST}:{SERVER_PORT}")
|
||||
|
||||
while True:
|
||||
# use select to wait for either server messages or user input
|
||||
read_sockets, _, _ = select.select([client_socket, sys.stdin], [], [])
|
||||
if os.name == 'nt': # Windows-specific logic
|
||||
import msvcrt
|
||||
client_socket.setblocking(False) # Set the socket to non-blocking mode
|
||||
|
||||
for sock in read_sockets:
|
||||
if sock == client_socket:
|
||||
# receive message from server
|
||||
while True:
|
||||
# Check for server messages
|
||||
try:
|
||||
server_message = client_socket.recv(BUFFER_SIZE).decode('utf-8')
|
||||
if not server_message:
|
||||
print("Disconnected from server")
|
||||
return
|
||||
print(f"\n{server_message}")
|
||||
print("> ", end="", flush=True)
|
||||
else:
|
||||
# prompt for user input
|
||||
client_message = input()
|
||||
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...")
|
||||
return
|
||||
|
||||
# send message to server
|
||||
break
|
||||
client_socket.send(client_message.encode('utf-8'))
|
||||
|
||||
else: # Linux/Unix-specific logic
|
||||
while True:
|
||||
# use select to wait for either server messages or user input
|
||||
read_sockets, _, _ = select.select([client_socket, sys.stdin], [], [])
|
||||
|
||||
for sock in read_sockets:
|
||||
if sock == client_socket:
|
||||
# receive message from server
|
||||
server_message = client_socket.recv(BUFFER_SIZE).decode('utf-8')
|
||||
if not server_message:
|
||||
print("Disconnected from server")
|
||||
return
|
||||
print(f"\n{server_message}")
|
||||
print("> ", end="", flush=True)
|
||||
else:
|
||||
# prompt for user input
|
||||
client_message = input()
|
||||
if client_message.strip() == "%!":
|
||||
print("Exiting chat...")
|
||||
return
|
||||
client_socket.send(client_message.encode('utf-8'))
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
finally:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue