1、安装依赖
npm install --save rsocket-core
npm install --save rsocket-websocket-client
2、组件代码
<template>
<div>
</div>
</template>
<script>
import { RSocketClient, JsonSerializer, IdentitySerializer } from 'rsocket-core';
import RSocketWebSocketClient from 'rsocket-websocket-client';
export default {
data(){
return{
}
},
created(){
// backend ws endpoint
const wsURL = 'ws://localhost:6565/rsocket';
// rsocket client
const client = new RSocketClient({
serializers: {
data: JsonSerializer,
metadata: IdentitySerializer
},
setup: {
keepAlive: 60000,
lifetime: 180000,
dataMimeType: 'application/json',
metadataMimeType: 'message/x.rsocket.routing.v0',
},
transport: new RSocketWebSocketClient({
url: wsURL
})
});
// error handler
const errorHanlder = (e) => console.log(e);
// response handler
const responseHanlder = (payload) => {
const li = document.createElement('li');
li.innerText = payload.data;
li.classList.add('list-group-item', 'small')
document.getElementById('result').appendChild(li);
}
// request to rsocket-websocket and response handling
const numberRequester = (socket, value) => {
socket.requestStream({
data: value,
metadata: String.fromCharCode('number.stream'.length) + 'number.stream'
}).subscribe({
onError: errorHanlder,
onNext: responseHanlder,
onSubscribe: subscription => {
subscription.request(100); // set it to some max value
}
})
}
const rsRequestResponse = (socket,msg) => {
// requestResponse模式下,服务端会返回一个payload,在RSocketJS中用Single表示
const single = socket.requestResponse({
data: msg
});
single.subscribe({
onComplete: payload => {
console.info(`[requestResponse]${payload.data.msg}`)
}
});
};
// once the backend connection is established, register the event listeners
client.connect().then(socket => {
// document.getElementById('n').addEventListener('change', ({srcElement}) => {
// numberRequester(socket, parseInt(srcElement.value));
// })
rsRequestResponse(socket)
}, errorHanlder);
},
methods:{
}
}
</script>
<style lang="scss" scoped>
</style>
|