Twisted Python - 将数据推送到websocket

Twisted Python - 将数据推送到websocket

问题描述:

我有一个与客户端连接的web-socket服务器。以下是代码: -Twisted Python - 将数据推送到websocket

from twisted.internet.protocol import Factory 
from twisted.protocols.basic import LineReceiver 
from twisted.internet import reactor 

class Chat(LineReceiver): 

    def __init__(self, users): 
     self.users = users 
     self.name = None 
     self.state = "GETNAME" 

    def connectionMade(self): 
     self.sendLine("What's your name?") 

    def connectionLost(self, reason): 
     if self.users.has_key(self.name): 
      del self.users[self.name] 

    def lineReceived(self, line): 
     if self.state == "GETNAME": 
      self.handle_GETNAME(line) 
     else: 
      self.handle_CHAT(line) 

    def handle_GETNAME(self, name): 
     if self.users.has_key(name): 
      self.sendLine("Name taken, please choose another.") 
      return 
     self.sendLine("Welcome, %s!" % (name,)) 
     self.name = name 
     self.users[name] = self 
     self.state = "CHAT" 

    def handle_CHAT(self, message): 
     # Need to send the message to the connected clients. 


class ChatFactory(Factory): 

    def __init__(self): 
     self.users = {} # maps user names to Chat instances 

    def buildProtocol(self, addr): 
     return Chat(self.users) 


reactor.listenTCP(8123, ChatFactory()) 
reactor.run() 

客户端连接到上述代码(服务器),并将数据发送到服务器。

现在,我已经有了另一个python脚本,基本上是一个报废web,处理它并最终需要将数据发送到连接的客户端的报废者。

script.py

while True: 
    # call `send_message` function and send data to the connected clients. 

我怎样才能实现呢?任何例子都会有很大的帮助!

UPDATE

After using Autobahn

我已经从第三方API获取数据的服务器。我想将这些数据发送到所有连接的网络套接字客户端。这里是我的代码: -

class MyServerProtocol(WebSocketServerProtocol): 
    def __init__(self): 
     self.connected_users = [] 
     self.send_data() 

    def onConnect(self, request): 
     print("Client connecting: {0}".format(request.peer)) 

    def onOpen(self): 
     print("WebSocket connection open.") 
     self.connected_users.append(self) # adding users to the connected_list 

    def send_data(self): 
     # fetch data from the API and forward it to the connected_users. 
     for u in self.users: 
      print 1111 
      u.sendMessage('Hello, Some Data from API!', False) 

    def onClose(self, wasClean, code, reason): 
     connected_users.remove(self) # remove user from the connected list of users 
     print("WebSocket connection closed: {0}".format(reason)) 


if __name__ == '__main__': 

    import sys 

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

    factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") 
    factory.protocol = MyServerProtocol  

    reactor.listenTCP(9000, factory) 
    reactor.run() 

我的服务器将永远不会收到一条消息或可能会接受,但就目前来说,没有这样的用例,因此没有必要OnMessage事件在这个例子中)。

如何编写我的send_data函数以便将数据发送给所有连接的客户端?

+1

什么'send_message'? “websockets”在哪里? –

+0

'send_message'将通过哪些功能将数据推送到连接的Web客户端(套接字)? – PythonEnthusiast

+1

“websockets”是一个特定的协议 - https://en.wikipedia.org/wiki/WebSocket - 它似乎没有用于你的示例代码。如果您确实需要WebSockets,请参考Autobahn。 –

你需要扭转编写软件时,为了避免这种模式:

while True: 
    # call `send_message` function and send data to the connected clients. 

Twisted是一个合作的多任务系统。 “合作”意味着你必须定期放弃对执行的控制,以便其他任务有机会运行。

twisted.internet.task.LoopingCall可以用于替代许多while ...环(尤其while True循环):

from twisted.internet.task import LoopingCall 
LoopingCall(one_iteration).start(iteration_interval) 

这将调用one_iterationiteration_interval秒。在这之间,它将放弃对执行的控制,以便其他任务可以运行。

制作one_iteration发送消息给客户只是给one_iteration一个引用该客户端(或那些客户端,如果有很多)。

这是FAQ How do I make Input on One Connection Result in Output on Another的变体。

如果你有一个包含所有客户的字典一个ChatFactory,只是通过该厂进行one_iteration

LoopingCall(one_iteration, that_factory) 

LoopingCall(lambda: one_iteration(that_factory)) 
+0

我想你没有理解我的问题。让我重新来一下。请看更新的问题。 – PythonEnthusiast