1

I have a WebSocket server that is receiving streams of messages from an MQTT source and the message is sent to a localhost server (port 8080). The message received is a stream of random numbers.

Python code for the Websocket server:

# Acts as localhost server
import websockets
import asyncio
import requests
import json

PORT = 3001

print("Server listening on Port " + str(PORT))

async def echo(websocket, path):
    print("A client just connected")
    try:
        async for message in websocket:
            hello ="test"
            text = message
            print("Received message from client: " + message)
            payload = {'value':message}
            r = requests.post('http://localhost:8080', params=payload)
            print(r)
            await websocket.send("Pong: " + text + message + hello)
    except websockets.exceptions.ConnectionClosed as e:
        print("A client just disconnected")

start_server = websockets.serve(echo, "localhost", PORT)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Example of message stream as printed out from log:

A client just connected
Received message from client: 35
<Response [200]>
A client just connected
Received message from client: 38
<Response [200]>
A client just connected
Received message from client: 38
<Response [200]>
A client just connected
Received message from client: 38
<Response [200]>
A client just connected
Received message from client: 33
<Response [200]>

Then, I attempt to read the numbers from 'http://localhost:8080' from my React frontend app using a GET request using Express and Axios However it didn't work and probably because I am not very experienced with the JS API packages. As such, how do I read the messages from my React app?

1 Answer 1

1

You could do this using npm i socket.io-client

const socket = io("http://localhost:8080"); // connects to server address


socket.on('connect', () => {
  console.log('connected to server');
});

socket.emit("Pong: ", "hello") // this is to send

/* this is to listen */
socket.on("value-to-listen-too", (params) => {
    ...
}

In your react app I would put the socket on a context. Then pass it whereever its needed. Then in the file where I would use socket I would use an effect hook like so

 useEffect(() => {

    socket.on("read-message", (message) => {
      someFunc(message)
    })

    return () => {
      // turn off sockets after exiting app / page
      socket.off("read-message")
    };
  }, [socket]);
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thanks for answering. So the socket would listen to my python WebSocket server? If so, how do i take the data as shown in the log? Sorry i'm really new to this
The socket listens to your python webserver. I already showed how to send (.emit) and receive data (.on) in my answer.

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.