magic-wormhole-transit-relay/ws_client.py

75 lines
2.1 KiB
Python
Raw Normal View History

2021-02-23 20:32:02 +00:00
from __future__ import print_function
2021-04-06 16:34:00 +00:00
import sys
2021-02-23 20:32:02 +00:00
from twisted.internet import endpoints
from twisted.internet.defer import (
Deferred,
inlineCallbacks,
)
2021-04-06 16:34:00 +00:00
from twisted.internet.task import react, deferLater
2021-02-23 20:32:02 +00:00
from autobahn.twisted.websocket import (
WebSocketClientProtocol,
WebSocketClientFactory,
)
class RelayEchoClient(WebSocketClientProtocol):
def onOpen(self):
2021-04-06 16:34:00 +00:00
self._received = b""
self.sendMessage(
u"please relay {} for side {}".format(
self.factory.token,
self.factory.side,
).encode("ascii"),
True,
2021-02-23 20:32:02 +00:00
)
def onMessage(self, data, isBinary):
print(">onMessage: {} bytes".format(len(data)))
print(data, isBinary)
if data == b"ok\n":
self.factory.ready.callback(None)
else:
2021-04-06 16:34:00 +00:00
self._received += data
2021-04-07 22:31:32 +00:00
if False:
# test abrupt hangup from receiving side
self.transport.loseConnection()
2021-02-23 20:32:02 +00:00
def onClose(self, wasClean, code, reason):
print(">onClose", wasClean, code, reason)
self.factory.done.callback(reason)
2021-04-06 16:34:00 +00:00
if not self.factory.ready.called:
self.factory.ready.errback(RuntimeError(reason))
2021-02-23 20:32:02 +00:00
@react
@inlineCallbacks
def main(reactor):
2021-04-06 16:34:00 +00:00
will_send_message = len(sys.argv) > 1
2021-02-23 20:47:22 +00:00
ep = endpoints.clientFromString(reactor, "tcp:localhost:4002")
f = WebSocketClientFactory("ws://127.0.0.1:4002/")
2021-04-06 16:34:00 +00:00
f.reactor = reactor
2021-02-23 20:32:02 +00:00
f.protocol = RelayEchoClient
f.token = "a" * 64
2021-04-06 16:34:00 +00:00
f.side = "0" * 16 if will_send_message else "1" * 16
2021-02-23 20:32:02 +00:00
f.done = Deferred()
f.ready = Deferred()
2021-04-07 22:28:19 +00:00
2021-02-23 20:32:02 +00:00
proto = yield ep.connect(f)
2021-04-06 16:34:00 +00:00
print("proto", proto)
2021-02-23 20:32:02 +00:00
yield f.ready
2021-04-07 22:28:19 +00:00
2021-02-23 20:32:02 +00:00
print("ready")
2021-04-06 16:34:00 +00:00
if will_send_message:
for _ in range(5):
print("sending message")
proto.sendMessage(b"it's a message", True)
yield deferLater(reactor, 0.2)
2021-02-23 20:32:02 +00:00
yield proto.sendClose()
2021-04-06 16:34:00 +00:00
print("closing")
2021-02-23 20:32:02 +00:00
yield f.done
2021-04-06 16:34:00 +00:00
print("relayed {} bytes:".format(len(proto._received)))
print(proto._received.decode("utf8"))