websocket长连接

注意:需要后台发送数据,或者使用node的pm2自拟后台

websocket安装:

 npm i ws -S

react中使用的代码:

import React from 'react'
import './styles.less'
import { Action } from '../../../node_modules/rxjs/internal/scheduler/Action';

export default class Home extends React.Component {
  constructor (props) {
    super(props)
    this.ws = new WebSocket("ws://localhost:8181")
    this.WebSocketTest()   
  }

  state = {
    name: '',
  }

  WebSocketTest = () => {
    if ('WebSocket' in window) {
        // 打开一个 web socket
        
        this.ws.onopen = () => {
          // Web Socket 已连接上,使用 send() 方法发送数据
          this.ws.send('发送数据')
          console.log("数据发送中...")
        }
        
        this.ws.onmessage = evt => { 
          var received_msg = evt.data
          console.log(received_msg, '333333333')
        }
        
        this.ws.onclose = () => { 
          // 关闭 websocket
          console.log("连接已关闭...") 
        }
    }
  }

  onSend = () => {
    this.ws.send('发送数据')
  }

  render () {
    return (
      <div className="pages-home">
        <button onClick={this.onSend}>sorket</button>
      </div>
    )
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。