-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatservercli.py
More file actions
174 lines (142 loc) · 4.92 KB
/
chatservercli.py
File metadata and controls
174 lines (142 loc) · 4.92 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
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
#!/usr/bin/env python3
import os
import sys
import socket
import threading
import hashlib
import datetime
HOST = '192.168.0.122'
PORT = 9090
accFileName = 'accounts.txt'
accFilePath = ''
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((HOST, PORT))
server.listen()
clients = []
usernames = []
passhashes = []
accFile = open(f"{accFilePath}{accFileName}",'r+')
accText = accFile.readlines()
accFile.close()
for line in accText:
clients.append(0)
lin = line.split('#')
usernames.append(lin[0])
passhashes.append(lin[1].strip())
def broadcast(message):
for client in clients:
try:
client.send(message.encode('utf-8'))
except AttributeError:
pass
def handle(client):
while True:
try:
msg = client.recv(1024).decode('utf-8')
message = '[{:%d-%m-%Y %H:%M}]'.format(datetime.datetime.now()) + f"<{usernames[clients.index(client)]}> {msg}"
if len(msg) > 1:
#logging
logFile = open('msg.log', 'a')
logFile.write(f"{message}\n")
logFile.close()
print(message)
#send the message to everyone
broadcast(message)
if msg == '':
#this should be triggered if the client becomes unreachable
username=usernames[clients.index(client)]
client.close()
clients[clients.index(client)] = 0
#logging
message = '[{:%d-%m-%Y %H:%M}]'.format(datetime.datetime.now()) + f"{username} disconnected.\n"
logFile = open('connect.log', 'a')
logFile2= open('msg.log', 'a')
logFile2.write(message)
logFile.write(message)
logFile.close()
logFile.close()
broadcast(message.replace('\n',''))
print(f"{username} disconnected.")
break
except KeyboardInterrupt:
pass
def receive():
while True:
client, address = server.accept()
client.send("LOGIN".encode('utf-8')) #requesting username from client
logindata = client.recv(1024).decode('utf-8').split('#') #taking their response
username = logindata[0]
passhash = logindata[1]
try:
usernames.index(username)
except ValueError:
client.send("BADUSERNAME".encode('utf-8'))
client.close()
continue
if clients[usernames.index(username)] != 0:
client.send("ALREADYLOGGED".encode('utf-8'))
client.close()
continue
try:
passhashes.index(passhash)
except ValueError:
client.send("BADPASSWORD".encode('utf-8'))
client.close()
continue
if usernames.index(username) == passhashes.index(passhash):
client.send("OK".encode('utf-8'))
clients[usernames.index(username)] = client
try:
logFile = open('msg.log', 'r')
client.send(logFile.read().encode('utf-8'))
logFile.close()
except:
pass
address = address[0]
msg1 = '[{:%d-%m-%Y %H:%M}]'.format(datetime.datetime.now()) + f"{username} connected to the server\n"
msg2 = '[{:%d-%m-%Y %H:%M}]'.format(datetime.datetime.now()) + f"{username} connected to the server from {str(address)}\n"
#logging
logFile = open('msg.log', 'a')
logFile2= open('connect.log','a')
logFile.write(msg1)
logFile2.write(msg2)
logFile.close()
logFile2.close()
print(msg2)
broadcast(msg1.replace('\n',''))
thread = threading.Thread(target=handle, args=(client,))
thread.daemon = True
thread.start()
elif usernames.index(username) != passhashes.index(passhash):
client.send("BADPASSWORD".encode('utf-8'))
client.close()
print ("Server running")
try:
logFile = open('log.txt', 'r')
print(logFile.read())
logFile.close()
except:
pass
try:
receive()
except KeyboardInterrupt:
broadcast('1')
for client in clients:
try:
client.close()
except AttributeError:
pass
server.close()
print("\nServer is stopping")
exit()
except BrokenPipeError or UnicodeDecodeError:
for client in clients:
try:
client.close()
except AttributeError:
pass
server.close()
clients = []
nicknames = []
os.execv(sys.argv[0], sys.argv)