add reconnecting WebSocket client

This commit is contained in:
Tobias Oberstein
2014-10-08 22:24:00 +02:00
parent f3ca81848f
commit 5ef2ac0580
3 changed files with 157 additions and 0 deletions

View File

@@ -0,0 +1,20 @@
# Auto Reconnecting WebSocket Client
This example demonstrates a WebSocket client that automatically retries connecting when the server connection is lost (or could not be established in the first place).
The reconnection schedule is doing proper exponential backoff. Please see Twisted documentation for [ReconnectingClientFactory](http://twistedmatrix.com/documents/current/api/twisted.internet.protocol.ReconnectingClientFactory.html)
## Running
Start the server in a first terminal:
python server.py
Now start the client in a second terminal:
python client.py
Then stop the server. The client looses the connection. Restart the server. The client will automatically reconnect to the server.
You can also start the client before starting the server. The client will connect when the server comes up (upon next reconnection schedule).

View File

@@ -0,0 +1,79 @@
###############################################################################
##
## Copyright (C) 2011-2014 Tavendo GmbH
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##
###############################################################################
from twisted.internet.protocol import ReconnectingClientFactory
from autobahn.twisted.websocket import WebSocketClientProtocol, \
WebSocketClientFactory
class MyClientProtocol(WebSocketClientProtocol):
def onConnect(self, response):
print("Server connected: {0}".format(response.peer))
def onOpen(self):
print("WebSocket connection open.")
def hello():
self.sendMessage(u"Hello, world!".encode('utf8'))
self.sendMessage(b"\x00\x01\x03\x04", isBinary = True)
self.factory.reactor.callLater(1, hello)
## start sending messages every second ..
hello()
def onMessage(self, payload, isBinary):
if isBinary:
print("Binary message received: {0} bytes".format(len(payload)))
else:
print("Text message received: {0}".format(payload.decode('utf8')))
def onClose(self, wasClean, code, reason):
print("WebSocket connection closed: {0}".format(reason))
class MyClientFactory(WebSocketClientFactory, ReconnectingClientFactory):
protocol = MyClientProtocol
def clientConnectionFailed(self, connector, reason):
print("Client connection failed .. retrying ..")
self.retry(connector)
def clientConnectionLost(self, connector, reason):
print("Client connection lost .. retrying ..")
self.retry(connector)
if __name__ == '__main__':
import sys
from twisted.python import log
from twisted.internet import reactor
log.startLogging(sys.stdout)
factory = MyClientFactory("ws://localhost:9000", debug = False)
reactor.connectTCP("127.0.0.1", 9000, factory)
reactor.run()

View File

@@ -0,0 +1,58 @@
###############################################################################
##
## Copyright (C) 2011-2014 Tavendo GmbH
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##
###############################################################################
from autobahn.twisted.websocket import WebSocketServerProtocol, \
WebSocketServerFactory
class MyServerProtocol(WebSocketServerProtocol):
def onConnect(self, request):
print("Client connecting: {0}".format(request.peer))
def onOpen(self):
print("WebSocket connection open.")
def onMessage(self, payload, isBinary):
if isBinary:
print("Binary message received: {0} bytes".format(len(payload)))
else:
print("Text message received: {0}".format(payload.decode('utf8')))
## echo back message verbatim
self.sendMessage(payload, isBinary)
def onClose(self, wasClean, code, reason):
print("WebSocket connection closed: {0}".format(reason))
if __name__ == '__main__':
import sys
from twisted.python import log
from twisted.internet import reactor
log.startLogging(sys.stdout)
factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
factory.protocol = MyServerProtocol
reactor.listenTCP(9000, factory)
reactor.run()