/
twisted-cometd-client.py
376 lines (303 loc) · 9.97 KB
/
twisted-cometd-client.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
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
from twisted.python import log
from twisted.web2.client import http
from twisted.web2 import resource, channel, stream, http_headers, responsecode
from twisted.internet import protocol, reactor, defer
from path import path
import urllib
import os
import md5
import time
import simplejson
import string
import base64
import types
class HTTPLineNotifierClientProtocol(http.HTTPClientProtocol):
def __init__(self, lineNotify=None, rawNotify=None, manager=None):
self.lineNotifier = lineNotify
self.rawNotifier = rawNotify
http.HTTPClientProtocol.__init__(self, manager)
def lineReceived(self, line):
http.HTTPClientProtocol.lineReceived(self, line)
if self.lineNotifier is not None:
self.lineNotifier(line)
def rawDataReceived(self, data):
http.HTTPClientProtocol.rawDataReceived(self, data)
if self.rawNotifier is not None:
self.rawNotifier(data)
# primary functions from the JavaScript client are:
# - init()
# - finishInit(type, data, evt, request) // called when handshake returns
# - deliver(messagesArr)
# - disconnect() // tears down connection on current transport
# - publish(channel, data, properties) // publishes data to server on channel
# - subscribe(channel, useLocalTopics, objOrFunc, funcName)
# - subscribed(channel, message)
# - unsubscribe(channel, useLocalTopics, objOrFunc, funcName)
# - unsubscribed(channel, message)
class CometdClient:
"""
This is a cometd client class. Unlike the JavaScript client, only
one connection type (mime-message-block) is supported.
"""
version = 0.1
minimumVersion = 0.1
def __init__(self, baseUri="/cometd", server="localhost", port=8080):
self.server = server
self.port = port
self.baseUri = baseUri
self.clientId = None
self.initialized = False
self.connected = False
self.authToken = ""
self.lastTimestamp = ""
self.lastId = None
self.handshakeDeferred = defer.Deferred()
self.commandClient = protocol.ClientCreator(reactor, http.HTTPClientProtocol)
self.channelClient = protocol.ClientCreator(reactor, HTTPLineNotifierClientProtocol)
self._isFirstLine = True
self._backlog = []
self._lines = []
self._buffer = ""
self._mimeBoundary = ""
self._handlers = {}
def _stockHeaders(self):
thead = http_headers.Headers()
thead.addRawHeader("Content-Type", "application/x-www-form-urlencoded")
thead.addRawHeader("Host", self.server)
return thead
def _getMessageRequest(self, message={}, rawheaders={}):
mstream = stream.MemoryStream(
urllib.urlencode({
"message": simplejson.dumps([ message ])
})
)
headers = self._stockHeaders()
for key in rawheaders.keys():
headers.addRawHeader(key, rawheaders[key])
req = http.ClientRequest( "POST",
self.baseUri,
headers,
mstream)
return req
def init(self):
# FIXME: need to add auth data to the handshakeObj!
handshakeObj = {
"channel": "/meta/handshake",
"version": self.version,
"minimumVersion": self.minimumVersion,
"supportedConnectionTypes": ["mime-message-block"]
}
d = self.commandClient.connectTCP(self.server, self.port)
"""
def printResponse(resp):
def _print(data):
log.msg(data)
stream.readStream(resp.stream, _print)
#.addCallback(printResponse)
"""
def _tcpInitFailure(proto):
log.err("_tcpInitFailure")
log.err(proto)
def _tcpInit(proto):
self.handshakeDeferred.addCallback(self.startup)
proto.submitRequest(self._getMessageRequest(handshakeObj)).addCallback(self._finishInit)
d.addCallback(_tcpInit)
d.addErrback(_tcpInitFailure)
def _finishInit(self, resp):
def handleJSON(jsonStr):
json = simplejson.loads(jsonStr)[0]
if not json["authSuccessful"]:
log.err("authentication failure!")
self.handshakeDeferred.errback(json)
return
if json["version"] < self.minimumVersion:
log.err("cometd protocol version mismatch. We wanted", self.minimumVersion, "but got", str(json["version"]))
self.handshakeDeferred.errback(json)
return
if not "mime-message-block" in json["supportedConnectionTypes"]:
log.err("desired transport type (mime-message-block) not supported by server")
self.handshakeDeferred.errback(json)
return
self.clientId = json["clientId"]
self.initialized = True
self.handshakeDeferred.callback(json)
# print json
stream.readStream(resp.stream, handleJSON)
def startup(self, handshakeData):
if self.connected:
print "ERROR: already connected!"
return
# print "startup start"
self._openTunnelWith({
"channel": "/meta/connect",
"clientId": self.clientId,
"connectionType": "mime-message-block"
})
# print "startup! end"
def _openTunnelWith(self, content):
d = self.channelClient.connectTCP(self.server, self.port)
def _tcpInit(proto):
# self.handshakeDeferred.addCallback(self.startup)
self.connected = True
proto.lineNotifier = self.handleLine
proto.rawNotifier = self.handleRaw
def _readResponse(resp):
# print "_readResponse"
def _print(data):
print data
stream.readStream(resp.stream, _print)
proto.submitRequest(
self._getMessageRequest(content)
).addCallback(_readResponse) # important to read from the stream!
d.addCallback(_tcpInit)
def _tunnelOpened(self, data):
# print "_tunnelOpened"
# print str(data)
pass
def handleLine(self, line):
# if self._isFirstLine:
# if line[0:2] == "--":
# print "first line!"
# print line
# self._isFirstLine = False
# else:
# print line
ctypeStr = "Content-Type: multipart/x-mixed-replace; boundary="
if line.find(ctypeStr) == 0:
self._mimeBoundary = "--"+line[len(ctypeStr):].strip()
def _handleLineStrip(self, line):
if line[0:2] == "--":
return line.strip()
elif line.find("Content-Type: ") == 0:
return line.strip()
else:
return line
def handleRaw(self, data):
# print "---------------------- raw data --------------------------"
# print data
# print "---------------------- end raw data --------------------------"
tdata = filter(
lambda x: len(x.strip()),
map(
self._handleLineStrip,
data.split("\n")
)
)
self._lines.extend(tdata)
# print "---------------- lines ---------------------"
# print self._lines
# print "--------------------------------------------"
if self._mimeBoundary in self._lines:
boundaryIndex = self._lines.index(self._mimeBoundary)
while 0 <= boundaryIndex <= 1:
self._lines = self._lines[1:]
boundaryIndex = self._lines.index(self._mimeBoundary)
while boundaryIndex > 1:
ctypeIndex = self._lines.index("Content-Type: text/plain")
jsonStr = string.join(self._lines[(ctypeIndex+1):boundaryIndex], "\n")
self.deliver(
simplejson.loads(jsonStr)
)
self._lines = self._lines[boundaryIndex:]
boundaryIndex = self._lines.index(self._mimeBoundary)
while boundaryIndex == 0:
self._lines = self._lines[1:]
if len(self._lines):
boundaryIndex = self._lines.index(self._mimeBoundary)
else:
boundaryIndex = -1
# print "---------------- lines ---------------------"
# print self._lines
# else:
# log.err("think we got a bad mime block!")
# print "---------------- data ---------------------"
# print data
def sendMessage(self, message, bypassBacklog=False):
if bypassBacklog or self.connected:
# message["connectionId"] = self.connectionId
message["clientId"] = self.clientId
d = self.channelClient.connectTCP(self.server, self.port)
def _msgAck(data):
print "_msgAck:",
print data
def _tcpInit(proto):
proto.submitRequest(
self._getMessageRequest(message)
) #.addCallback(_msgAck)
d.addCallback(_tcpInit)
else:
self._backlog.append(message)
def deliver(self, messageList):
for item in messageList:
self._deliver(item)
# reactor.iterate()
def _deliver(self, message):
print "------------------- delivering message ----------------------"
print message
if not message.has_key("channel"):
# print "message has no channel!"
log.err("message has no channel!")
log.info(str(essage))
return
self.lastMessage = message
if message.has_key("timestamp"):
self.lastTimestamp = message["timestamp"]
if message.has_key("id"):
self.lastId = message["id"]
if len(message["channel"]) > 5 and \
str(message["channel"])[0:5] == "/meta":
if not message["successful"]:
# print ("error for channel: "+message["channel"])
log.err("error for channel: ", message["channel"])
return
if message["channel"] == "/meta/connect":
log.msg("connected!")
self.connectionId = message["connectionId"]
self.connected = True
self._processBacklog()
elif message["channel"] == "/meta/reconnect":
self.connected = True
self._processBacklog()
elif message["channel"] == "/meta/subscribe":
self.subscribed(message["subscription"], message)
elif message["channel"] == "/meta/unsubscribe":
self.unsubscribed(message["subscription"], message)
def _processBacklog(self):
log.msg("processing the backlog which is ", len(self._backlog), " items long")
while len(self._backlog):
self.sendMessage(self._backlog.pop(0), True)
def subscribed(self, channel, message):
log.msg("subscribed:", channel)
pass
def unsubscribed(self, channel, message):
log.msg("unsubscribed:", channel)
pass
def subscribe(self, channel, callback):
# print "subscribing to "+channel
self.sendMessage({
"channel": "/meta/subscribe",
"subscription": str(channel)
})
if channel not in self._handlers:
self._handlers[channel] = [ callback ]
elif callback not in self._handlers[channel]:
self._handlers[channel].append(callback)
def unsubscribe(self, channel, callback):
self.sendMessage({
"channel": "/meta/unsubscribe",
"subscription": str(channel)
})
# FIXME: not complete!
pass
if __name__=="__main__":
def _move(data):
print "/magnets/move"
print data
clients = []
for x in xrange(50):
clients.append(CometdClient())
reactor.callWhenRunning(clients[x].subscribe, "/magnets/move", _move)
clients[x].init()
# client.subscribe("/magnets/move", _move)
reactor.run()
# vim:ts=4:noet: