0

I want to make one real-time chat application using websockets and the frontend is angular5.

So, I create websocket in purepython and backend is Django and frontend is angular5.

Myquestion is when i create websocket service in python. So, do i have to make websockets services in angular too?

this is my python websocket service

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

So, i want to create two user can send and receive messages.so must be design in angular ..

so i am asking that i already create one service in python so do i have to create websocket service(Observable subscribers) in angular too?

2
  • is this question still open ? Commented Jul 26, 2018 at 19:35
  • no @madjaoue it is close... Commented Jul 27, 2018 at 7:01

1 Answer 1

2

In your angular side, you should open a connection indeed.

This is how you can use Observables to communicate with your server :

Client side

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

To send a message, simply use :

ws.send('test')

Server Side

You can use the demo in https://pypi.org/project/websocket-client/ to build your websocket server.

to import WebSocket :

pip install websocket-client

Then :

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()
Sign up to request clarification or add additional context in comments.

3 Comments

okay... Thnks..If you i have some tutorial link .. please suggest me.. so i can refer..
With this, you should be able to send and receive messages between angular and python. Your next step is to redirect these messages to the right person. This is not a tutorial, but a solved similar problem. Maybe it can help you : stackoverflow.com/questions/45356426/…
I updated my comment with code for a WebSocket server in python. Hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.