-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
275 lines (236 loc) · 9.05 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
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
import struct
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
from resizeimage import resizeimage
import pymysql
from PIL import ImageTk, Image
import os
import random
def change(image):
basewidth = 300
img = Image.open(image)
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
img.save(image)
def rec(client):
size = struct.unpack("i", client.recv(struct.calcsize("i")))[0]
username = ""
while len(username) < size:
msg = client.recv(size - len(username))
if not msg:
return None
username += msg.decode('utf8')
return username
def accept_incoming_connections():
"""Sets up handling for incoming clients."""
while True:
client, client_address = SERVER.accept()
print("%s:%s has connected." % client_address)
addresses[client] = client_address
Thread(target=handle_client, args=(client,)).start()
'''req = client.recv(1024).decode("utf8")
print(req)
size = struct.unpack("i", client.recv(struct.calcsize("i")))[0]
username = ""
while len(username) < size:
msg = client.recv(size - len(username))
if not msg:
return None
username += msg.decode('utf8')
size = struct.unpack("i", client.recv(struct.calcsize("i")))[0]
password = ""
while len(password) < size:
msg = client.recv(size - len(password))
if not msg:
return None
password += msg.decode('utf8')
print(req,username,password)
if req=='register':
with conn.cursor() as cursor:
sql ="INSERT INTO `members` (`username`, `password`) VALUES (%s,%s)"
cursor.execute(sql,(username,password))
conn.commit()
conn.close()
client.send(bytes("correct",'utf8'))
print(req)
Thread(target=handle_client, args=(client,username)).start()
if req=='login':
req='incorrect'
while 1==1:
with conn.cursor() as cursor:
sql ="SELECT `id`, `password` FROM `members` WHERE `username`=%s"
cursor.execute(sql, (username,))
result=cursor.fetchone()
if(result==None):
print('does not exist')
client.send(bytes("incorrect",'utf8'))
req = client.recv(1024).decode("utf8")
#print(result[1])
elif result[1]!=password:
print('username or password incorrect')
client.send(bytes("incorrect",'utf8'))
req = client.recv(1024).decode("utf8")
elif result[1]==password:
break
size = struct.unpack("i", client.recv(struct.calcsize("i")))[0]
username = ""
while len(username) < size:
msg = client.recv(size - len(username))
if not msg:
return None
username += msg.decode('utf8')
size = struct.unpack("i", client.recv(struct.calcsize("i")))[0]
password = ""
while len(password) < size:
msg = client.recv(size - len(password))
if not msg:
return None
password += msg.decode('utf8')
print('username exist')
print('req is ',req)
client.send(bytes("correct",'utf8'))
Thread(target=handle_client, args=(client,username)).start()
#Thread(target=handle_client, args=(client,)).start()'''
def rec_login(client,conn):
username=rec(client)
password=rec(client)
while(True):
with conn.cursor() as cursor:
print('checking for',username,password)
sql ="SELECT `id`, `password` FROM `members` WHERE `username`=%s"
cursor.execute(sql, (username,))
result=cursor.fetchone()
if(result==None):
print('does not exist')
client.send(bytes("incorrect",'utf8'))
req = rec(client)
#print(result[1])
elif result[1]!=password:
print('username or password incorrect')
client.send(bytes("incorrect",'utf8'))
req = rec(client)
elif result[1]==password:
print('correct')
break
username=rec(client)
password=rec(client)
#req = client.recv(1024).decode("utf8")
conn.close()
message="correct"
client.send( struct.pack("i", len(message)) + bytes(message,'utf8'))
return username
def rec_register(client,conn):
username=rec(client)
password=rec(client)
email=rec(client)
print(username,password,email)
while(True):
with conn.cursor() as cursor:
sql1 ="SELECT `id` FROM `members` WHERE `username`=%s"
cursor.execute(sql1, (username,))
result1=cursor.fetchone()
sql2 ="SELECT `id` FROM `members` WHERE `email`=%s"
cursor.execute(sql2, (email,))
result2=cursor.fetchone()
if(result1!=None):
print('username unavailable')
client.send(bytes("username unavailable",'utf8'))
if(result2!=None):
print('email is already registered')
client.send(bytes("email is already registered",'utf8'))
else:
break
with conn.cursor() as cursor:
sql ="INSERT INTO `members` (`username`, `email`, `password`, `blacklist`) VALUES (%s,%s,%s,%s)"
cursor.execute(sql,(username,email,password,1))
conn.commit()
client.send(bytes("correct",'utf8'))
req = rec(client)
username=rec_login(client,conn)
return username
def handle_client(client): # Takes client socket as argument.
"""Handles a single client connection."""
conn = pymysql.connect(host='127.0.0.1', user='user', passwd='password', db='data')
req = rec(client)
username=""
password=""
if(req=='login'):
username=rec_login(client,conn)
if(req=='register'):
print('register')
username=rec_register(client,conn)
welcome = 'Welcome %s! If you ever want to quit, press quit to exit.' % username
client.send( struct.pack("i", len(welcome)) + bytes(welcome,'utf8'))
msg = "welcome %s has joined the chat!" % username
broadcast(msg)
clients[client] = username
while True:
msg = rec(client)
print(msg)
if(msg == '*.img*'):
s=username+" : "
broadcast(s)
rec_img(client)
elif msg != "{quit}":
print('1')
sr=username+": "+msg
broadcast(sr)
else:
print('2')
client.send(bytes("{quit}", "utf8"))
client.close()
del clients[client]
broadcast("%s has left the chat." % username)
break
def send_img(client):
i=random.randint(1,10000)
client.send( struct.pack("i", len("ser"+str(i)+".jpg")) + bytes("ser"+str(i)+".jpg",'utf8'))
img=open('ser.jpg','rb')
l = img.read(1024)
while (l):
print ('Sending...')
client.send(l)
l = img.read(1024)
img.close()
print('done sending')
client.send( struct.pack("i", len("done")) + bytes("done",'utf8'))
def rec_img(client):
print("recieving image")
f = open('ser.jpg','wb')
l = client.recv(1024)
while (l):
print ("Receiving...")
f.write(l)
l = client.recv(1024)
last=l[-4:]
print(str(last))
if(last==b'done'):
break
f.close()
print('done recieving')
broadcast("*.img*")
change('ser.jpg')
for sock in clients:
send_img(sock)
def broadcast(msg): # prefix is for name identification.
"""Broadcasts a message to all the clients."""
for sock in clients:
sock.send( struct.pack("i", len(msg)) + bytes(msg,'utf8'))
clients = {}
addresses = {}
HOST = ''
PORT = input('enter port: ')
BUFSIZ = 1024
ADDR = (HOST, int(PORT))
SERVER = socket(AF_INET, SOCK_STREAM)
SERVER.bind(ADDR)
if __name__ == "__main__":
SERVER.listen(5)
print("Waiting for connection...")
ACCEPT_THREAD = Thread(target=accept_incoming_connections)
ACCEPT_THREAD.start()
ACCEPT_THREAD.join()
SERVER.close()