-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.py
81 lines (62 loc) · 1.92 KB
/
Server.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 2 20:37:59 2017
@author: aj
"""
import socket
import select
import sys
from _thread import *
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# checks whether sufficient arguments have been provided
if len(sys.argv) != 3:
print ("Correct usage: script, IP address, port number")
exit()
# takes the first argument from command prompt as IP address
IP_address = str(sys.argv[1])
# takes second argument from command prompt as port number
Port = int(sys.argv[2])
print("starting up on %s port %s" % (IP_address, Port))
server.bind((IP_address, Port))
server.listen(100)
list_of_clients = []
def clientthread(conn, addr):
conn.send("Welcome to this chatroom!\n Start Messaging".encode())
while True:
try:
message = conn.recv(2048).decode()
if message:
"""prints the message and address of the
user who just sent the message on the server
terminal"""
print ("<" + addr[0]+":"+ str(addr[1]) + "> " + message)
# Calls broadcast function to send message to all
message_to_send = "<" + addr[0]+":"+ str(addr[1]) + "> " + message
broadcast(message_to_send, conn)
else:
remove(conn)
except:
continue
def broadcast(message, connection):
for clients in list_of_clients:
if clients!=connection:
try:
clients.send(message.encode())
except:
clients.close()
# if the link is broken, we remove the client
remove(clients)
def remove(connection):
if connection in list_of_clients:
list_of_clients.remove(connection)
while True:
conn, addr = server.accept()
list_of_clients.append(conn)
# prints the address of the user that just connected
print (addr[0] + ":"+ str(addr[1]) +" connected")
# creates and individual thread for every user that connects
start_new_thread(clientthread,(conn,addr))
conn.close()
server.close()