【问题标题】:webSocket.send() is not executed in react js?webSocket.send() 没有在 react js 中执行?
【发布时间】:2021-10-05 09:45:56
【问题描述】:

我在 reactjs 中使用 WebSocket,但是 WebSocket.send 没有在 onClick 事件上执行。 这里我创建了 WebSocket

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

连接到 WebSocket

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

这是我的 onClick 函数

  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");
    }
  };

所以这是我的问题,我无法在我的代码中找到错误或问题。

【问题讨论】:

  • 你能发布控制台输出吗?
  • 是的,首先连接 ws,然后在函数中随机调用所有条件,但代码行 ``` ws.send("message")`` 被跳过或不执行。
  • 更改 console.log(‘click’) 以同时记录 we.readyStatemessage。这可能会给你一些关于原因的线索。
  • 'sending message' 控制台也被打印出来了

标签: javascript reactjs websocket


【解决方案1】:

试试这个 W3CWebSocket。另外,我认为在 ws/notification 仔细检查您的终点是否正确后,通知后没有“/”。

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;

【讨论】:

  • 我也尝试过这种方法。但不幸的是它也不起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-20
  • 1970-01-01
  • 2021-12-16
  • 2012-06-26
  • 2016-12-20
  • 2021-12-15
相关资源
最近更新 更多