ws-event-bus
v1.2.1
Published
event bus between frontend and backend
Downloads
14
Readme
ws-event-bus
介绍
开发时使用的event bus;利用ws服务器作为中转。
安装教程
npm i ws -D
npm i ws-event-bus -D
使用说明
浏览器端:
html:
<body>
<button id="btn1">btn1</button>
<button id="btn2">btn2</button>
</body>
js(需要打包):
import WSS from 'ws-event-bus'
function getClient(id) {
let ws = new WSS({
id,
url: 'ws://localhost:8080/'
})
ws.on('message', (data) => {
console.log(id + ' get message >>>>', data)
})
ws.on('wait', (data,response) => {
console.log(id + ' wait >>>>', response)
})
return ws
}
let w1 = getClient('w1')
let w2 = getClient('w2')
function click1(){
w1.send('this is w1+', {
to: 'w2'
}).then(res => {
console.log('w1 get reply')
})
}
function click2(){
w2.reply(w2.waiting[0],'value')
}
document.getElementById('btn1').onclick = click1
document.getElementById('btn2').onclick = click2
server:
const WSS = require('ws-event-bus/dist/server.js').default
const path = require('path')
let server = new Server({
port:8080
})
server.static(path.resolve(process.cwd()),'./');//静态资源
server.start()
nodejs:
const WSS = require('ws-event-bus').default
function getClient(id) {
let ws = new WSS({
id,
url: 'ws://localhost:8080/'
})
ws.on('message', (data) => {
console.log(id + ' get message>>>>', data)
})
ws.on('wait', (data, response) => {
console.log(id + ' wait >>>>', response)
})
return ws
}
let w1 = getClient('w1')
let w2 = getClient('w2')
function click1() {
w1.send('this is w1+', {
to: 'w2'
}).then(res => {
console.log('w1 sucewss++++', res)
})
}
function click2() {
w2.reply(w2.waiting[0],'value')
}
click1()
setTimeout(() => {
click2()
}, 3000)
setTimeout(() => {}, 100000)