最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

无法在不重新加载页面的情况下获取套接字数据,并与以下代码反应

网站源码admin21浏览0评论

无法在不重新加载页面的情况下获取套接字数据,并与以下代码反应

无法在不重新加载页面的情况下获取套接字数据,并与以下代码反应

nodejs中的套接字服务器,它将数据发送到客户端(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');
  });
})

用于接收套接字数据和显示的反应前端(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;

从上述两个文件中,我在重新加载页面时获取套接字数据,但在不重新加载页面的情况下无法获取数据,我不知道为什么它在React App中表现得如此,我必须在我的应用程序中批量接收数据,这就是为什么是必需的。我只是为此创建了一个演示,如果有人知道React中的套接字而不是plz帮助。

回答如下:

此代码解决的问题-

发布评论

评论列表(0)

  1. 暂无评论