Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

217
Visualizações
How do I send message from localhost to React frontend

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda