-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatClient.py
More file actions
80 lines (67 loc) · 1.6 KB
/
chatClient.py
File metadata and controls
80 lines (67 loc) · 1.6 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
import socket
import sys
import os
import threading
import time
import re
if(len(sys.argv) <= 1):
print("Needs IP as arguement")
sys.exit()
ip = sys.argv[1]
def loadCookie():
global cookie
cookie = "NULL"
if(os.path.isfile("cookie")):
cookie = open("cookie","r").read()
print("Loaded cookie")
return cookie
socketSemaphore = threading.BoundedSemaphore(1)
cookie = loadCookie()
def saveCookie():
global cookie
open("cookie","w").write(cookie)
print("saved cookie")
def main():
postDaemon = threading.Thread(target=postReader,daemon=True)
postDaemon.start()
while True:
m = input()
reply = sendToSocket(m,ip)
if(reply is not None):
parseReply(reply)
def sendToSocket(message,ip):
global cookie
socketSemaphore.acquire()
try:
s = socket.socket()
s.connect((ip,80))
s.send(makePost(message,cookie).encode())
reply = s.recv(1000)
except ConnectionRefusedError:
print("Server is offline")
socketSemaphore.release()
return None
socketSemaphore.release()
s_reply = reply.decode()
m = re.search(r"Set-Cookie:(?P<cookie>[a-z0-9]+);",s_reply)
if(m is not None):
if(m.group("cookie") is not None):
cookie = m.group("cookie")
print("Cookie set to",cookie)
saveCookie()
return s_reply
def postReader():
while True:
time.sleep(1)
r = sendToSocket("",ip)
if(r is not None):
parseReply(r)
def parseReply(r):
messages = r.split("`")
for i in range(1,len(messages)):
print(messages[i].split("; ")[1])
def makePost(message,cookie):
post = "POST / HTTP/1.1\r\nCookie: " + cookie + "\r\n\r\n" + message + "\r\n\r\n"
return post
if __name__ == "__main__":
main()