Autobahn with sendMessage using threading and twisted

99封情书 提交于 2019-12-24 04:49:08

问题


From this thread (sendMessage from outside in autobahn running in separate thread) I am trying to get the code below working.

But I am getting the following error:

  File "/usr/local/lib/python2.7/dist-packages/autobahn/websocket/protocol.py", line 2421, in sendMessage
    assert(type(payload) == bytes)
exceptions.AssertionError: 

Can anybody tell me where I am going wrong?

from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory

import threading
from twisted.python import log
from twisted.internet import reactor
import sys
import time

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))


class Connection(threading.Thread):
    def __init__(self):
        super(Connection, self).__init__()
        self.factory=WebSocketServerFactory("ws://localhost:9000", debug=False)
    def run(self):
        log.startLogging(sys.stdout)
        self.factory.protocol = MyServerProtocol()
        reactor.listenTCP(9000, self.factory)
        reactor.run(installSignalHandlers=0)

    def send(self, data):

        data = format(data.encode('utf8'))
        protocol = MyServerProtocol()
        reactor.callFromThread(protocol.sendMessage, protocol, data) 


connection = Connection()
connection.daemon = True
connection.start()
print "Running"

for x in range(1, 100):

    connection.send("hello")
    time.sleep(2)

Thanks

EDIT 1:

Full Error:

2015-04-30 07:27:09+0930 [-] Log opened.
2015-04-30 07:27:09+0930 [-] WebSocketServerFactory starting on 9000
2015-04-30 07:27:09+0930 [-] Running
2015-04-30 07:27:09+0930 [-] Starting factory <autobahn.twisted.websocket.WebSocketServerFactory object at 0x7fa97f888a50>
2015-04-30 07:27:09+0930 [-] Unhandled Error
    Traceback (most recent call last):
      File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
        self.run()
      File "/home/me/Development/eclipse/new_workspace/Engine2/websockets/maybe.py", line 39, in run
        reactor.run(installSignalHandlers=0)
      File "/usr/local/lib/python2.7/dist-packages/twisted/internet/base.py", line 1192, in run
        self.mainLoop()
      File "/usr/local/lib/python2.7/dist-packages/twisted/internet/base.py", line 1201, in mainLoop
        self.runUntilCurrent()
    --- <exception caught here> ---
      File "/usr/local/lib/python2.7/dist-packages/twisted/internet/base.py", line 797, in runUntilCurrent
        f(*a, **kw)
      File "/usr/local/lib/python2.7/dist-packages/autobahn/websocket/protocol.py", line 2421, in sendMessage
        assert(type(payload) == bytes)
    exceptions.AssertionError: 

EDIT 2:

Removed threading:

from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory

from twisted.python import log
from twisted.internet import reactor
import sys

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))

    def send(self, data):

        data = format(data.encode('utf8'))
        protocol = MyServerProtocol()
        reactor.callFromThread(protocol.sendMessage, protocol, data) 

class Test(MyServerProtocol):

    def __init__(self):
        self.factory=WebSocketServerFactory("ws://localhost:9000", debug=False)
        log.startLogging(sys.stdout)
        self.factory.protocol = MyServerProtocol
        reactor.listenTCP(9000, self.factory)
        reactor.run(installSignalHandlers=0)


Test = Test()
Test.send("hello")

print "Running"

回答1:


you can't start thread like that in twisted

from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory

from twisted.python import log
from twisted.internet import reactor
import sys

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))

    def send(self, data):

        data = format(data.encode('utf8'))
        protocol = MyServerProtocol()
        reactor.callFromThread(protocol.sendMessage, protocol, data) 

class Test(MyServerProtocol):

    def __init__(self):
        self.factory=WebSocketServerFactory("ws://localhost:9000", debug=False)
        log.startLogging(sys.stdout)
        self.factory.protocol = MyServerProtocol
        reactor.listenTCP(9000, self.factory)
        reactor.run(installSignalHandlers=0)


Test = Test()


print "Running"


来源:https://stackoverflow.com/questions/29955373/autobahn-with-sendmessage-using-threading-and-twisted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!