-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
104 lines (86 loc) · 2.93 KB
/
Copy pathserver.py
File metadata and controls
104 lines (86 loc) · 2.93 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import socket
import threading
import sys
#list of special commands
commands = {
" /train/": "sl",
" /cowsay": "cowsay",
" /xcowsay": "xcowsay",
" /cowthink": "cowthink"
}
def help():
print("Usage: python3 server.py host port")
print("Ex: python3 server.py 127.0.0.1 1060")
exit()
#data for connection
if(len(sys.argv)==3):
host = sys.argv[1]
port = int(sys.argv[2])
else:
help()
#Starting the server
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
#Lists for clients and nicknames
clients = []
nicknames = []
#Sending messages to all connected clients except the one sent message
def broadcast(message, index):
if(len(message.decode('UTF-8').split(':')) == 2):
msg = message.decode('UTF-8').split(':')[1]
if(msg in commands or msg.split('?')[0] in commands or msg==" emogi -help" or msg==" cowsay -help"):
for client in clients:
client.send(message)
elif(len(msg.split('?')[0].split('!'))==3):
new_msg = msg.split('?')[0].split('!')
if(new_msg[1]=="-f"):
for client in clients:
client.send(message)
else:
for client in clients:
if(clients.index(client)!=index):
client.send(message)
else:
for client in clients:
if(clients.index(client)!=index):
client.send(message)
#Handling messages from clients
def handle(client):
while(True):
try:
#broadcasting messages
message = client.recv(2048)
index = clients.index(client)
broadcast(message, index)
except:
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast('{} left!'.format(nickname).encode('UTF-8'), index)
print('{} left the server'.format(nickname))
nicknames.remove(nickname)
break
#receive or listening function
def receive():
while(True):
#accept connection
client, address = server.accept()
print("connected with {}".format(str(address)))
#request and store nickname
client.send('NICK'.encode('UTF-8'))
nickname = client.recv(2048).decode('UTF-8')
nicknames.append(nickname)
clients.append(client)
client.send('First line'.encode('UTF-8'))
#print and broadcast nickname
print("Joined person's nickname is {}".format(nickname))
index = clients.index(client)
broadcast("{} joined the server!".format(nickname).encode('UTF-8'), index)
#client.send("Successfully connected to server!".encode('UTF-8'))
#start handling thread for client
thread = threading.Thread(target=handle, args=(client,))
thread.start()
print("Server is listening.....")
receive()