0

Socket server in nodejs which sends data to client (server.js)-

const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: 8000 })
wss.on('connection', ws => {
  ws.on('message', message => {
    console.log(`${message}`)
  })
  ws.send(JSON.stringify({
    type:'random_number2',
    interval: 2000, 
    take: 100, 
  }));
  ws.on('close', function() {
    console.log('closing connection');
  });
})

React front-end for receiving the socket data and display (socket.js)-

import React, { Component } from 'react';

const url = 'ws://localhost:8000';
const connection = new WebSocket(url);

class Socket extends Component {

  state = {
    response : ''
  }
  //componentWillMount() {
componentDidMount() {

    connection.onopen = () => {
      connection.send('Hello, Client is connected!!') 
    }

    setInterval( connection.onmessage = (message) => {
       this.setState({response : message.data});

        console.log("message");
        console.log(message);

        // if(this.state.response !== message.data){
        //   this.setState({response : message.data});
        // }

        console.log('message.data');  
        console.log(message.data);    
        },5000);

    connection.onclose = () => {
      console.log('disconnected');
      // automatically try to reconnect on connection loss
      }

    connection.onerror = err => {
        console.error(
            "Socket encountered error: ",
            err.message,
            "Closing socket"
        );
       // connection.close();
    };

  }

  render() {
    return (
      <div>
        Server Message
        {this.state.response}
      </div>
    );
  }
}

export default Socket;

From these 2 above files I am getting socket data on page reload but unable to get data without page reload I don't know why it is behaving like that in react App I have to receive data in bulk in my app that's why it is needed. I just created a demo for that if anyone know about socket in react than plz help.

0

2 Answers 2

1

This is for anyone having the same problem. It's solved by declaring your WebSocket connection after the state as @Ritika has pointed out. like in hooks, inside useEffect.

useEffect(() => {
    // const connection = new WebSocket('ws://localhost:8000')
    //    Or if your are importing your connection from another file:
    const ws = connection();
   ....
  }, []);
Sign up to request clarification or add additional context in comments.

Comments

0

Problem Resolved with this code -

import React, { Component } from 'react';
import { w3cwebsocket as W3CWebSocket } from "websocket";

const url = 'ws://localhost:8000';

class Socket extends Component {

state = {
   response : ''
}

connection = new WebSocket(url);
componentDidMount() {
this.connection.onopen = () => {
  this.connection.send('Hello, Client is connected!!') 
}

this.connection.onmessage = (message) => {
    this.setState({response : message.data});    
}

this.connection.onclose = () => {
  console.log('disconnected');
}

this.connection.onerror = err => {
    console.error(
        "Socket encountered error: ",
        err.message,
        "Closing socket"
    );
   };
 }

render() {
return (
  <div>
    Socket Server Message
    {this.state.response}
  </div>
);
}
}

export default Socket;

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.