forked from dpallot/simple-websocket-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebSockPortMapper.py
More file actions
94 lines (78 loc) · 2.5 KB
/
WebSockPortMapper.py
File metadata and controls
94 lines (78 loc) · 2.5 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
#!/usr/bin/python
from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer
import time
import socket
import threading
class mysocket:
'''demonstration class only
- coded for clarity, not efficiency
'''
def __init__(self, sock=None):
if sock is None:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
else:
self.sock = sock
def connect(self, host, port):
self.sock.connect((host, port))
def mysend(self, msg):
totalsent = 0
MSGLEN=len(msg)
while totalsent < MSGLEN:
sent = self.sock.send(msg[totalsent:])
if sent == 0:
raise RuntimeError("socket connection broken")
totalsent = totalsent + sent
def myreceive(self):
msg = ''
MSGLEN=120
while len(msg) < MSGLEN:
chunk = self.sock.recv(MSGLEN-len(msg))
if chunk == '':
raise RuntimeError("socket connection broken")
msg = msg + chunk
return msg
def myclose(self):
self.sock.close()
class SimpleEcho(WebSocket):
def SockFun(self):
try:
ms=mysocket()
ms.connect("127.0.0.1",7778)
self.FlagDict["sockexists"]=1
while (1):
print "inside ",self.FlagDict
if ( self.FlagDict["Data"] ):
time.sleep(1)
msg=str(self.FlagDict["Data"])
#self.FlagDict["Data"]=''
ms.mysend(msg)
else:
time.sleep(10)
a=ms.myreceive()
self.sendMessage(a)
self.FlagDict["sockexists"]=0
self.FlagDict["threadexists"]=0
ms.myclose()
except Exception as a:
self.FlagDict["sockexists"]=0
self.FlagDict["threadexists"]=0
ms.myclose()
print "error in SockFun",a
def handleMessage(self):
if self.data is None:
self.data = ''
else:
self.CheckThread()
def handleConnected(self):
print self.address, 'connected'
try:
self.FlagDict={}
self.FlagDict["sockexists"]=0
self.FlagDict["threadexists"]=0
self.FlagDict["Data"]=self.data
except:
print "error in handle connect"
def handleClose(self):
print self.address, 'closed'
server = SimpleWebSocketServer('', 8000, SimpleEcho)
server.serveforever()