1. 程式人生 > >nodejs訊息推送之ws

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>