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