Create the client, and modify the server.
This commit is contained in:
parent
5443d01d5c
commit
12eb4fb3f5
2 changed files with 53 additions and 6 deletions
|
|
@ -0,0 +1,47 @@
|
|||
import socket
|
||||
import sys
|
||||
import select
|
||||
|
||||
SERVER_HOST = 'localhost'
|
||||
SERVER_PORT = 8181
|
||||
BUFFER_SIZE = 1024
|
||||
|
||||
def main():
|
||||
# create a socket object
|
||||
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
try:
|
||||
# connect to the server
|
||||
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], [], [])
|
||||
|
||||
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
|
||||
|
||||
# send message to server
|
||||
client_socket.send(client_message.encode('utf-8'))
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
finally:
|
||||
client_socket.close()
|
||||
print("Connection closed")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
Add table
Add a link
Reference in a new issue