-
Notifications
You must be signed in to change notification settings - Fork 0
/
visualizer.py
105 lines (82 loc) · 2.82 KB
/
visualizer.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
import txws
from Queue import Queue
from twisted.web import http
from twisted.internet import protocol, reactor
def init_state(t_dict):
pass
class BitClient(protocol.Protocol):
message_list = []
'''
Responsible for grabbing TCP connection to BitTorrent client.
Gets callback on dataReceived initiating a broadcast to all
websockets
'''
def dataReceived(self, data):
print 'received some data:' + '\n\t' + data
self.message_list.append(data)
if WebSocket.websockets:
WebSocket.broadcast(data)
class MyRequestHandler(http.Request):
clientHTML = open('client.html').read()
clientJS = open('client.js').read()
resources = {
'/': clientHTML,
'/client.js': clientJS
}
def process(self):
print 'process got called'
self.setHeader('Content-Type', 'text/html')
if self.path in self.resources:
self.write(self.resources[self.path])
else:
self.setResponseCode(http.NOT_FOUND,
'Sorry, dogg. We dont have those here')
self.finish()
class MyHTTP(http.HTTPChannel):
print 'HTTP protocol object initialized'
requestFactory = MyRequestHandler
class MyHTTPFactory(http.HTTPFactory):
def buildProtocol(self, addr):
http_protocol = MyHTTP()
return http_protocol
class WebSocket(protocol.Protocol):
websockets = []
@classmethod
def add_socket(self, ws):
print 'adding a websocket'
WebSocket.websockets.append(ws)
@classmethod
def broadcast(self, message):
for ws in WebSocket.websockets:
ws.message_queue.put(message)
ws.send_all_messages()
def connectionMade(self):
self.message_queue = Queue()
for i in range(len(BitClient.message_list)):
self.message_queue.put(BitClient.message_list[i])
self.send_all_messages()
def connectionLost(self, reason):
print 'connection lost for', self
WebSocket.websockets.remove(self)
def send_all_messages(self):
print 'SENDING ALL MESSAGES'
while not self.message_queue.empty():
self.transport.write(self.message_queue.get())
class MyWSFactory(protocol.Factory):
def buildProtocol(self, addr):
print 'building a WebSocket object'
ws = WebSocket()
WebSocket.add_socket(ws)
print WebSocket.websockets
return ws
class BitClientFactory(protocol.Factory):
def buildProtocol(self, addr):
print 'building a BitClient object'
bc = BitClient()
return bc
bit_client = BitClient()
print 'Listening for BitTorrent clients on port 8002'
reactor.listenTCP(8002, BitClientFactory())
reactor.listenTCP(80, MyHTTPFactory())
reactor.listenTCP(8001, txws.WebSocketFactory(MyWSFactory()))
reactor.run()