-
Notifications
You must be signed in to change notification settings - Fork 0
/
WebSocket_server.py
executable file
·105 lines (63 loc) · 2.64 KB
/
WebSocket_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
from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory
import sys
from twisted.python import log
from twisted.internet import reactor
from server_lib import gpio
import json
import os
import threading
import logging
import parse_message, TCP_client, socket, errno, traceback
class ws_server(WebSocketServerProtocol):
def send(self, message):
self.sendMessage(message)
def onConnect(self, request):
logging.info("Client connecting: {0}".format(request.peer))
def onOpen(self):
pass
def onMessage(self, payload, isBinary):
try:
logging.debug("Received %s" % (payload.decode('utf8')))
obj = json.loads(payload.decode('utf8'))
if obj['DestinationAddress'] == 'self':
parse_message.onMessage(obj, config_file, self.send)
else:
# self.relayMessage(obj)
(threading.Thread(target=self.relayMessage, args=(obj,))).start()
except Exception as e:
logging.exception('')
def onClose(self, wasClean, code, reason):
logging.info("connection closed: {0}".format(reason))
def relayMessage(self, obj):
logging.debug("Destination is not self - passing on to destination - %s" % obj['DestinationAddress'])
dest_addr = obj['DestinationAddress'].split(':')[0]
dest_port = obj['DestinationAddress'].split(':')[1]
try:
q_reply = TCP_client.relaymessage(dest_addr, dest_port, json.dumps(obj))
if q_reply != "":
q_reply_obj = json.loads(q_reply)
q_reply_obj['Sender'] = "%s:%s" % (dest_addr, dest_port)
self.send(json.dumps(q_reply_obj))
except socket.error, v:
errorcode=v[0]
errmsg = {
"Sender": "self",
"MessageType": "ErrorMessage",
"Error": "TCP connection to %s failed (%s)" % (obj['DestinationAddress'], v)
}
self.send(json.dumps(errmsg))
logging.exception('')
pathname = os.path.dirname(sys.argv[0])
fullpath = os.path.abspath(pathname)
config_file = fullpath + "/config/config.json"
with open(config_file) as data_file:
data = json.load(data_file)
port = int(data['WebSocket']['port'])
address = "ws://localhost:%s" % port
threads = {}
def main():
# log.startLogging(sys.stdout)
factory = WebSocketServerFactory(address, debug=False)
factory.protocol = ws_server
reactor.listenTCP(port, factory)
reactor.run()