-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
67 lines (57 loc) · 2.74 KB
/
Copy pathserver.py
File metadata and controls
67 lines (57 loc) · 2.74 KB
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
import threading
import socket
host = 'localhost' #input("Host IP: ")
port = 25565 #int(input("Port: "))
try:
room_ids = eval(input("Room IDs: "))
except:
room_ids=[0]
ROOMS = {} #{Room-ID:[[client],[username]]}
# checking if user provided Room IDs, and creating the room
if len(room_ids):
for i in room_ids:
ROOMS[i]=[[],[]]
# initializing a Internet(AF_INET), TCP(SOCK_STREAM) server socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port)) # binding the server to the provided ip and port
server.listen() # listening for incomming connections
#Function to send messages to clients in specified room
def broadcast(message,room_id):
for client in ROOMS[room_id][0]:
client.send(message)
# Function to handle clients ie recieving messages and sending them, and disconnecting users
def handle_client(client,room_id):
while True:
try:
message = client.recv(1024) # recieving message from client (upto 1024 bytes)
broadcast(message,room_id)
except: # To remove client from chatroom if the client disconnects or some error occurs
index = ROOMS[room_id][0].index(client)
ROOMS[room_id][0].remove(client)
client.close() # closing the connection
username = ROOMS[room_id][1][index]
broadcast(f'{username} has left the chat room!'.encode('utf-8'),room_id)
ROOMS[room_id][1].remove(username)
break
# Function to establish connection with clients
def receive():
while True:
print('Server is running and listening ...')
conn, address = server.accept() # accepting the connection from clients
print(f'connection is established with {str(address)}')
conn.send('/<@username>/'.encode('utf-8')) # asking for username
username = conn.recv(1024).decode('utf-8') # recieving username (upto 1024 bytes)
conn.send('/<@room_id>/'.encode('utf-8')) # asking for Room ID
room_id = int(conn.recv(512).decode('utf-8')) # recieving Room ID (upto 512 bytes)
if room_id != 0 and room_id not in room_ids:
conn.send(f'There is no chatroom with the ID: {str(room_id)}, Connecting to Chatroom-0'.encode('utf-8'))
room_id = 0
ROOMS[room_id][1].append(username)
ROOMS[room_id][0].append(conn)
print(f'The usernames of this client is {username}'.encode('utf-8'))
broadcast(f'{username} has connected to the chat room'.encode('utf-8'),room_id)
conn.send('you are now connected!'.encode('utf-8'))
thread = threading.Thread(target=handle_client, args=(conn,room_id)) # running handle_client() for each user on separate threads
thread.start()
if __name__ == "__main__":
receive()