3

I have the below websocket server taking connections from web clients, and broadcasting data to all of the clients when certain keys are pressed on any of the clients. Everything is working just fine in that sector. I have two external Python applications doing various things on the server, however, and I need the websocket server to respond to their activities, as well. How can I connect to the websocket server from those applications, or is it even possible?

websocket server:

class Control(WebSocket):
    def handle(self):
        if self.data == "Left":
            Return = update.leftArrow()
            ClassValues = read_Class()
            LineValue = read_Line()
            message = "Line " + str(ClassValues[Return[1]][LineValue[Return[1]]])
        elif self.data == "Right":
            Return = update.rightArrow()
            LineValue = read_Line()
            message = "Line " + str(ClassValues[Return[1]][LineValue[Return[1]]])
        elif self.data == "Up":
            Return = update.upArrow()
            message = "Control " + str(Return[1])
        elif self.data == "Down":
            Return = update.downArrow()
            message = "Control " + str(Return[1])
        else:
            Return = [False, 0]
        if Return[0]:
            for client in self.server.connections.itervalues():
                client.sendMessage(message)

server = WebSocketServer('', 8000, Control)
server.serve_forever()

3 Answers 3

2

You could make use of the websockets module to connect to your websocket. I think the documentation available on that page is better than any explanation I could give here. It's also pretty simple and easy to understand.

Sign up to request clarification or add additional context in comments.

Comments

1

Based on new-dev-123's input, I have the following solutions:

Python < 3.6

import asyncio
import websockets

if TestCondition:
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(SendMessage(message))

@asyncio.coroutine
def SendMessage(message):
    websocket = yield from websockets.connect('ws://localhost:8000')
    try:
        yield from websocket.send(message)
    finally:
        yield from websocket.close()

Python >= 3.6:

import websockets, asyncio

async def Forward(message):
        url = 'ws://localhost:8000'
        async with websockets.connect(url) as websocket:
                await websocket.send(message)
def xmit_Loop(message):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.run_until_complete(Forward(message))

Comments

1

This piece of code will listen to the server's messages and print them to the client's screen.

pip install websockets
import asyncio
import websockets


async def handler(websocket):
    while True:
        message = await websocket.recv()
        print(message)


async def main():
    url = "ws://localhost:8181"
    async with websockets.connect(url) as ws:
        await handler(ws)
        await asyncio.Future()  # run forever


if __name__ == "__main__":
    asyncio.run(main())

Comments

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.