0

I am working with WebSocket in reactjs, but WebSocket.send is not executing on the onClick event. here I create WebSocket

 const ws = new WebSocket("ws://192.168.18.112:8000/ws/notification/");

connect to WebSocket

 ws.onopen = (e) => {
    console.log("connect");
  };

here is my onClick function

  const sendNotification = (e) => {
    console.log("click");
    if (ws.readyState === WebSocket.OPEN && message !== "") {
      ws.send("message");
      console.log("Sending message"); // this console is execute
    } else if (ws.readyState === WebSocket.CONNECTING) {
      ws.addEventListener("open", () => sendNotification());
      console.log("Connecting state");
      console.log("Not Send");
    } else {
      console.log("nothing happen");
    }
  };

so here is my problem I am unable to find bug or problem in my code.

4
  • Can you post the console output? Commented Oct 5, 2021 at 9:57
  • yes first the ws is connected, and than in function all conditions are call randomly but the line of code ``` ws.send("message")``` is skiped or not executing. Commented Oct 5, 2021 at 10:01
  • Change console.log(‘click’) to also log we.readyState and message. That might give you some clues about the cause. Commented Oct 5, 2021 at 10:05
  • 'sending message' console was also printed out Commented Oct 5, 2021 at 10:09

1 Answer 1

0

try this W3CWebSocket. Also i don't think there si a "/" after notification after ws/notification double check if your end point correct or not.

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

const client = new W3CWebSocket('ws://192.168.18.112:8000/ws/notification/');

class App extends Component {
  componentWillMount() {
    client.onopen = () => {
      console.log('WebSocket Client Connected');
    };
    client.onmessage = (message) => {
      console.log(message);
    };
  }
  
  render() {
    return (
      <div>
        Practical Intro To WebSockets.
      </div>
    );
  }
}

export default App;
Sign up to request clarification or add additional context in comments.

1 Comment

I have tried this approach too. but unfortunately its also not working

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.