nodejs消息推送之ws

nodejs服务器端,如何消息的类型为test就返回消息,反之则群发:

const WebSocket = require('ws');
const wss = new WebSocket.Server({port:3030})
const connection = {}

wss.on('connection',ws => {
    ws.on('message',message => {
        console.log(JSON.stringify(connection))
        message = JSON.parse(message)
        if(message.type === 'test') {
            connection[message.id] = ws
            console.log(connection)
            console.log('received: %s',JSON.stringify(message))
            if(!!connection[message.id])
                connection[message.id].send(JSON.stringify(message))
        }else {
            ws.clients.forEach(function each(client) {
                client.send(message);
            });
        }
            
    });
})

nodejs之客户端:

const WebSocket = require('ws');
const ws = new WebSocket('ws://127.0.0.1:3030');


ws.on('open',() =>{
    let msg = {type:'test',id:1}
    ws.send(JSON.stringify(msg));
})

ws.on('error', err => {
    console.log(err)
})

ws.on('message',data => {
    console.log(data)
})

ws.on('close',(code,reason) => {
    console.log(code);
    console.log(reason+'=========='+typeof reason)
})

html页面客户端:


<!DOCTYPE html>
<html>
<head>
	<title>skynet websocket example</title>
</head>
<body>
	<script>
	var ws = new WebSocket("ws://127.0.0.1:3030");
	
	ws.onopen = function(){
		alert("open");
		ws.send("WebSocket  hellowrold!!");
	};
	ws.onmessage = function(ev){
		alert(ev.data);
	};
	ws.onclose = function(ev){
		alert("close");
	};
	ws.onerror = function(ev){
		console.log(ev);
		alert("error");
	};
	</script>
</body>
<html>

猜你喜欢

转载自blog.csdn.net/swimming_in_IT_/article/details/83146752