-
Notifications
You must be signed in to change notification settings - Fork 3
/
chat_server.py
226 lines (213 loc) · 10.5 KB
/
chat_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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
"""
Created on Tue Jul 22 00:47:05 2014
@author: alina, zzhang
"""
import time
import socket
import select
import sys
import string
import indexer
import json
import pickle as pkl
from chat_utils import *
import chat_group as grp
class Server:
def __init__(self):
self.new_clients = [] #list of new sockets of which the user id is not known
self.logged_name2sock = {} #dictionary mapping username to socket
self.logged_sock2name = {} # dict mapping socket to user name
self.all_sockets = []
self.group = grp.Group()
#start server
self.server=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind(SERVER)
self.server.listen(5)
self.all_sockets.append(self.server)
#initialize past chat indices
self.indices={}
# sonnet
# self.sonnet_f = open('AllSonnets.txt.idx', 'rb')
# self.sonnet = pkl.load(self.sonnet_f)
# self.sonnet_f.close()
self.sonnet = indexer.PIndex("AllSonnets.txt")
def new_client(self, sock):
#add to all sockets and to new clients
print('new client...')
sock.setblocking(0)
self.new_clients.append(sock)
self.all_sockets.append(sock)
def login(self, sock):
#read the msg that should have login code plus username
try:
msg = json.loads(myrecv(sock))
if len(msg) > 0:
if msg["action"] == "login":
name = msg["name"]
if self.group.is_member(name) != True:
#move socket from new clients list to logged clients
self.new_clients.remove(sock)
#add into the name to sock mapping
self.logged_name2sock[name] = sock
self.logged_sock2name[sock] = name
#load chat history of that user
if name not in self.indices.keys():
try:
self.indices[name]=pkl.load(open(name+'.idx','rb'))
except IOError: #chat index does not exist, then create one
self.indices[name] = indexer.Index(name)
print(name + ' logged in')
self.group.join(name)
mysend(sock, json.dumps({"action":"login", "status":"ok"}))
else: #a client under this name has already logged in
mysend(sock, json.dumps({"action":"login", "status":"duplicate"}))
print(name + ' duplicate login attempt')
else:
print ('wrong code received')
else: #client died unexpectedly
self.logout(sock)
except:
self.all_sockets.remove(sock)
def logout(self, sock):
#remove sock from all lists
name = self.logged_sock2name[sock]
pkl.dump(self.indices[name], open(name + '.idx','wb'))
del self.indices[name]
del self.logged_name2sock[name]
del self.logged_sock2name[sock]
self.all_sockets.remove(sock)
self.group.leave(name)
sock.close()
#==============================================================================
# main command switchboard
#==============================================================================
def handle_msg(self, from_sock):
#read msg code
msg = myrecv(from_sock)
if len(msg) > 0:
#==============================================================================
# handle connect request
#==============================================================================
msg = json.loads(msg)
if msg["action"] == "connect":
to_name = msg["target"]
from_name = self.logged_sock2name[from_sock]
if to_name == from_name:
msg = json.dumps({"action":"connect", "status":"self"})
# connect to the peer
elif self.group.is_member(to_name):
to_sock = self.logged_name2sock[to_name]
self.group.connect(from_name, to_name)
the_guys = self.group.list_me(from_name)
msg = json.dumps({"action":"connect", "status":"success"})
for g in the_guys[1:]:
to_sock = self.logged_name2sock[g]
mysend(to_sock, json.dumps({"action":"connect", "status":"request", "from":from_name}))
else:
msg = json.dumps({"action":"connect", "status":"no-user"})
mysend(from_sock, msg)
#==============================================================================
# handle messeage exchange: one peer for now. will need multicast later
#==============================================================================
elif msg["action"] == "exchange":
from_name = self.logged_sock2name[from_sock]
the_guys = self.group.list_me(from_name)
#said = msg["from"]+msg["message"]
said2 = text_proc(msg["message"], from_name)
self.indices[from_name].add_msg_and_index(said2)
for g in the_guys[1:]:
to_sock = self.logged_name2sock[g]
self.indices[g].add_msg_and_index(said2)
mysend(to_sock, json.dumps({"action":"exchange", "from":msg["from"], "message":msg["message"]}))
# mysend(to_sock, json.dumps({'action':'translate','from':msg['from'],'message':msg["message"],'request':"do you want to translate it?"}))
#==============================================================================
# listing available peers
#==============================================================================
elif msg["action"] == "list":
from_name = self.logged_sock2name[from_sock]
msg = self.group.list_all(from_name)
mysend(from_sock, json.dumps({"action":"list", "results":msg}))
#==============================================================================
# retrieve a sonnet
#==============================================================================
elif msg["action"] == "poem":
poem_indx = int(msg["target"])
from_name = self.logged_sock2name[from_sock]
print(from_name + ' asks for ', poem_indx)
poem = self.sonnet.get_poem(poem_indx)
poem = '\n'.join(poem).strip()
print('here:\n', poem)
mysend(from_sock, json.dumps({"action":"poem", "results":poem}))
#==============================================================================
# time
#==============================================================================
elif msg["action"] == "time":
ctime = time.strftime('%d.%m.%y,%H:%M', time.localtime())
mysend(from_sock, json.dumps({"action":"time", "results":ctime}))
#==============================================================================
# search
#==============================================================================
elif msg["action"] == "search":
term = msg["target"]
from_name = self.logged_sock2name[from_sock]
print('search for ' + from_name + ' for ' + term)
# search_rslt = (self.indices[from_name].search(term))
search_rslt = '\n'.join([x[-1] for x in self.indices[from_name].search(term)])
print('server side search: ' + search_rslt)
mysend(from_sock, json.dumps({"action":"search", "results":search_rslt}))
#==============================================================================
# the "from" guy has had enough (talking to "to")!
#==============================================================================
elif msg["action"] == "disconnect":
from_name = self.logged_sock2name[from_sock]
the_guys = self.group.list_me(from_name)
self.group.disconnect(from_name)
the_guys.remove(from_name)
if len(the_guys) == 1: # only one left
g = the_guys.pop()
to_sock = self.logged_name2sock[g]
mysend(to_sock, json.dumps(
{"action": "disconnect", "msg": "Everyone left\nThis chat is ended."}))
# ==============================================================================
# now i am going to translate the message into different languages!
# ==============================================================================
# elif msg['action']=='translate':
# translator = translator.Translator()
# from_lang = translator.decect_language(msg['message'])
# to_lang=msg['language']
# translation = translator.translateBaidu(msg['message'], from_lang, to_lang)
# from_name = self.logged_sock2name[from_sock]
# said2 = text_proc(translation, from_name)
# self.indices[from_name].add_msg_and_index(said2)
#
# mysend(from_sock, json.dumps({"action": "translated", "from": msg["from"], "translation": translation,'language':to_lang}))
#==============================================================================
# the "from" guy really, really has had enough
#==============================================================================
else:
#client died unexpectedly
self.logout(from_sock)
#==============================================================================
# main loop, loops *forever*
#==============================================================================
def run(self):
print ('starting server...')
while(1):
read,write,error=select.select(self.all_sockets,[],[])
print('checking logged clients..')
for logc in list(self.logged_name2sock.values()):
if logc in read:
self.handle_msg(logc)
print('checking new clients..')
for newc in self.new_clients[:]:
if newc in read:
self.login(newc)
print('checking for new connections..')
if self.server in read :
#new client request
sock, address=self.server.accept()
self.new_client(sock)
def main():
server=Server()
server.run()
main()