-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
70 lines (55 loc) · 2.18 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
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import socket, select, cPickle, collections, chat_pb2
def send_data(sock, data):
try:
sock.send(cPickle.dumps(data))
except:
print("Error: probably broken pipe")
def recv_data(sock):
try:
return cPickle.loads(sock.recv(4096))
except:
return None
host, port = "127.0.0.1", 12345
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((host, port))
server_socket.listen(5)
print("Server listening at port " + str(port))
CONNECTION_LIST = [server_socket]
CONNECTION_DETAILS = dict()
CHANNEL_CONNECTIONS = dict()
def new_message(connections, sender_socket, nick, message):
msg = chat_pb2.message()
msg.text = nick + ": " + message
for conn in connections:
if conn is not sender_socket:
send_data(conn, ("message", msg))
while True:
#Ignoring write and error sockets.
read_sockets, _, _ = select.select(CONNECTION_LIST, [], [])
for sock in read_sockets:
#New connection
if sock == server_socket:
sockfd, addr = server_socket.accept()
CONNECTION_LIST.append(sockfd)
#Message from client
else:
data = recv_data(sock)
if data:
if (data[0] == "join"):
Details = collections.namedtuple('Details', 'channel nick')
channel = data[1].channel
nick = data[1].nick
CONNECTION_DETAILS[sock] = Details(channel, nick)
if CHANNEL_CONNECTIONS.has_key(channel):
CHANNEL_CONNECTIONS[channel].append(sock)
else:
CHANNEL_CONNECTIONS[channel] = [sock]
elif (data[0] == "message"):
channel = CONNECTION_DETAILS[sock].channel
nick = CONNECTION_DETAILS[sock].nick
msg = data[1].text
new_message(CHANNEL_CONNECTIONS[channel], sock, nick, msg)
server_socket.close()