使用websocket python + django + angular的聊天应用

时间:2018-07-17 12:36:26

标签: python django angular websocket

我想使用websockets创建一个实时聊天应用程序,并且前端是angular5。

因此,我在purepython中创建了websocket,后端是Django,前端是angular5。

我的问题是当我在python中创建websocket服务时。那么,我是否也必须以角度提供websockets服务?

这是我的python websocket服务

async def consumer_handler(websocket):
    global glob_message
    while True:
        message = await websocket.recv()
        await glob_message.put(message)
        print("this went in glob_message: {}".format(message))

async def producer_handler(websocket):
    global glob_message
    while True:
        message = await glob_message.get()
        await websocket.send(message)

async def handler(websocket, path):
    producer_task = asyncio.ensure_future(producer_handler(websocket))
    consumer_task = asyncio.ensure_future(consumer_handler(websocket))
    done, pending = await asyncio.wait(
        [consumer_task, producer_task],
        return_when=asyncio.FIRST_COMPLETED,
    )

    for task in pending:
        task.cancel()

if __name__ == '__main__':
    glob_message = asyncio.Queue()
    start_server = websockets.serve(
            handler,
            '127.0.0.1', 8788)
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()

所以,我想创建两个可以发送和接收消息的用户。因此必须设计成角形..

所以我要问我已经在python中创建了一项服务,所以我也必须以角度创建websocket服务(可观察的订户)吗?

1 个答案:

答案 0 :(得分:1)

在角形一侧,您确实应该打开连接。

这是使用Observables与服务器通信的方式:

客户端

// open the socket connection
const ws = new WebSocket('ws://127.0.0.1:8788')

// when opened, print all messages
ws.onopen = open => { 
      Observable.fromEvent(ws, 'message')
        .subscribe(message => console.log(message)) 
      }

要发送消息,只需使用:

ws.send('test')

服务器端

您可以使用https://pypi.org/project/websocket-client/中的演示来构建Websocket服务器。

导入WebSocket:

pip install websocket-client

然后:

import websocket
try:
    import thread
except ImportError:
    import _thread as thread
import time

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws):
    print("### closed ###")

def on_open(ws):
    def run(*args):
        for i in range(3):
            time.sleep(1)
            ws.send("Hello %d" % i)
        time.sleep(1)
        ws.close()
        print("thread terminating...")
    thread.start_new_thread(run, ())


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://127.0.0.1:8788",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()