chattle/client.py

49 lines
1.5 KiB
Python
Raw Normal View History

2021-09-30 01:21:18 +02:00
__author__ = "Kieran Osborne"
__version__ = "0.0.1"
__status__ = "Development"
if (__name__ == "__main__"):
2021-10-01 01:16:27 +02:00
import chattle
2021-09-30 01:21:18 +02:00
import config
import socket
import select
import sys
2021-09-30 01:21:18 +02:00
2021-10-01 01:16:27 +02:00
username = input("username: ")
address = (config.host, config.port)
2021-09-30 01:21:18 +02:00
print("Starting connection to", address)
2021-09-30 01:21:18 +02:00
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
server_socket.setblocking(False)
server_socket.connect_ex(address)
2021-09-30 01:21:18 +02:00
2021-10-01 01:16:27 +02:00
# Input may be written by the user or received from the server. Both cases have to be handled.
inputs = [sys.stdin, server_socket]
2021-09-30 01:21:18 +02:00
while True:
2021-10-01 01:16:27 +02:00
# Listen for input.
readable_io, _, _ = select.select(inputs, [], [])
2021-09-30 01:21:18 +02:00
for io in readable_io:
if (io == server_socket):
2021-10-01 01:16:27 +02:00
response_data = io.recv(config.message_max)
if not response_data:
exit(0)
print(response_data.decode("utf-8"))
elif (io == sys.stdin):
2021-10-01 01:16:27 +02:00
# Messages produced by this client are written to the terminal locally, rather than sending it to
# server to then receive it back.
line = sys.stdin.readline()
if not line.startswith("/"):
sys.stdout.write("<You> ")
sys.stdout.write(line)
sys.stdout.flush()
2021-10-01 01:16:27 +02:00
server_socket.send(chattle.encode_message(username, line))
2021-09-30 01:21:18 +02:00