react中调用websock(react-stomp)

53 篇文章 3 订阅

使用场景:我在做项目的时候遇到这样一个功能,后台实时的向前台发送消息,前台接收到后,已弹窗形式展示出来,一开始的方案是我前台不停的轮询接口,但是被否定了,最终决定使用socke来实现。

使用步骤

1.在命令窗口npm install react-stomp;

2.在组建中引入react-stomp(import SockJsClient from 'react-stomp');

3.在组件中直接使用;(https://www.npmjs.com/package/react-stomp#example-usage

import React from 'react';
import SockJsClient from 'react-stomp';
 
class SampleComponent extends React.Component {
  constructor(props) {
    super(props);
    state={
       data:""
    }
  }
 
  sendMessage = (msg) => {//发送消息
    this.clientRef.sendMessage('/topics/all', msg);
  }
  disconnect = (a) => {//断开连接
   this.clientRef.disconnect()
  }
  connect = () => {//建立连接
    this.clientRef.connect();
  }
  onMessage=(msg,topic)=>{//接收到消息的回调 msg后台返回的消息,topic是主题
    //这里拿到msg就可以使用了
     this.setState({
        data:msg
      })
  }
  render() {
    return (
      <div>
        <SockJsClient 
            url='http://localhost:8080/ws' //地址
            topics={['/topics/all']}  //主题
            onMessage={ this.onMessage }//接收到消息的回调
            ref={ (client) => { this.clientRef = client }} /> //显示到具体元素上
            headers={username:abc}  //携带的参数
            onDisconnect={(err)=>{console.log(连接失败)} //连接失败的回调
            sendMessage={this.client.send(topic, opt_headers, msg)} //发送消息
          />
      </div>
    );
  }
}

SockeClient有三个方法 :

1.connect()建立连接

2.disconnect()断开连接

3.SendMessage(topic, msg, opt_headers = {})发送消息(参数1:发送的主题,与topics致,参数2:发送的数据,参数三:携带的头部比如:username等)

SockeClient的props

url:是连接地址(http://localhost:8080/ws)

topics:是具体连接的主题比如(连接地址是http://localhost:8080/ws,topics就是具体的主题http://localhost:8080/ws下面的topics/all);

onMessage:收到消息的回调;

onDisconnect:连接失败的回调;

headers:可以携带一些参数,比入username等等;

onConnectFailure:无法建立连接的回调;

 autoReconnect:如果断开连接是否重新连接;

遇到的坑和报错(只是我自己别人不一定有)

1.我使用的时候报了个跨域问题

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

于是我配了个代理可以行的通了(但是反复断开连接,几次后就再也连不上了),但是会报很多问题,最后配合后端(得知soket连接根本没跨域这一说)。

具体文档API请参考(英文看不懂可以翻译)https://github.com/lahsivjar/react-stomp/blob/HEAD/API.md;

 

 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

崽崽的谷雨

漫漫前端路,摸爬滚打

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值