-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
81 lines (56 loc) · 2.08 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# Importing sockets for low level implementation of networks
import socket
# Importing select to poll between the user input and received message
import select
# Getting input from terminal and writing output to terminal
import sys
# creating the client_socket object and adding the TCP/IP and IPv4 protocol
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# IP and PORT of the socket
IP = "127.0.0.1"
PORT = 42069
# Header length used to receive the username
HEADER_LENGTH = 10
# Let's connect to the server!
client_socket.connect((IP, PORT))
# Handling Ctrl+C in a very cool way
import signal
def sigint_handler(signum, frame):
print('\n Disconnecting from server')
sys.exit()
signal.signal(signal.SIGINT, sigint_handler)
# Getting the input of username
my_username = input("Username: ")
# Clever function to send username to the server
# Format
# Header: length_of_username
# Body: Username
def sendUsernameToServer(my_username):
username = my_username.encode('utf-8')
username_header = f"{len(username):<{HEADER_LENGTH}}".encode('utf-8')
client_socket.send(username_header + username)
# Using the above function
sendUsernameToServer(my_username)
# polling between user input and message received from the server
sockets_list = [sys.stdin, client_socket]
while True:
# checking for I/O in read_sockets
read_sockets, write_socket, error_socket = select.select(
sockets_list, [], [])
for socket in read_sockets:
# If socket == client_socket, we got a message
if socket == client_socket:
message = socket.recv(2048)
if not len(message):
print("Connection closed by server")
sys.exit()
print(message.decode('utf-8'))
else:
# Else, we can send a message
message = sys.stdin.readline()
message = message.encode('utf-8')
client_socket.send(message)
#sys.stdout.write(str(my_username) + " > ")
# sys.stdout.write(message.decode('utf-8'))
sys.stdout.flush()
client_socket.close()