2015-03-01 20 views
5

MyServerProtocol sınıfının dışından sendMessage yöntemini aramak ve bağlı istemcilere bir ileti göndermek istiyorum. Bunu yapmak için threading kullanıyorum.Dışarıdan iş parçacığı içinde ayrı bir iş parçacığı içinde çalışan ileti kutusu

Bu kodu kullandığınızda:

from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory 
from twisted.internet import reactor 
import threading 

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

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

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

    def send(self, data): 
     reactor.callFromThread(self.factory.protocol.sendMessage, self.factory.protocol, data) 

connection = Connection() 
connection.daemon = True 
connection.start() 
connection.send('test') 

bu hata olur:

connection.send('test') 
reactor.callFromThread(self.factory.protocol.sendMessage, self.factory.protocol, data) 
AttributeError: 'Connection' object has no attribute 'factory' 

çizgiyi connection.send('test') açıklama denerseniz, bu hata olur:

TypeError: 'NoneType' object is not iterable 

neler kodumda sorun mu var?

Bunu doğru şekilde yapıyorum mu? Veya protokol sınıfının dışından müşterilere mesaj göndermek için başka bir yolu var mı?

Teşekkürler. senin "init (öz):" üzere

+0

mu self.factory var? Start() ile send() arasında bir uyku koymayı ve kontrol etmeyi deneyin. Ayrıca, bir hata ayıklayıcı kullanın. – Raito

+0

Hiç bunu nasıl anlamaya mı? Aynı problemi yaşıyorum. – someuser

cevap

0

eklenti self.factory aşağıya bakınız:

from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory 
    from twisted.internet import reactor 
    import threading 

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

      self.sendMessage(payload, isBinary) 

     def onClose(self, wasClean, code, reason): 
      print("WebSocket connection closed: {0}".format(reason)) 


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

     def send(self, data): 
      reactor.callFromThread(self.factory.protocol.sendMessage, self.factory.protocol, data) 

    connection = Connection() 
    connection.daemon = True 
    connection.start() 
    connection.send('test') 
+0

bu parçacığı da akranlarının birden fazla bağlantı kolu mu? – hietpasd

3

[orada] sunucu sınıfı dışından müşteriler mesaj göndermek için başka bir yoludur?

ben mesaj göndermek için böyle bir şey yapmak. Web uygulamamı çalıştırmak için twisted kullanıyorum.

import json 
from autobahn.twisted.websocket import WebSocketServerProtocol 
from twisted.internet import reactor 

class MyProtocol(WebSocketServerProtocol): 
    connections = list() 

    def onConnect(self, request): 
     self.connections.append(self) 

    def onClose(self, wasClean, code, reason): 
     self.connections.remove(self) 

    @classmethod 
    def broadcast_message(cls, data): 
     payload = json.dumps(data, ensure_ascii = False).encode('utf8') 
     for c in set(cls.connections): 
      reactor.callFromThread(cls.sendMessage, c, payload) 


# Somewhere else 
MyProtocol.broadcast_message({'greeting': 'Hello world'}) 

Bu Doğru ™ olup olmadığını bilmiyorum, ama benim için iyi çalışır. Gönderdiğiniz çağırdığınızda

İlgili konular