码迷,mamicode.com
首页 > Web开发 > 详细

我写的websocket推送例子,每隔5秒服务器向客户端浏览器发送消息(node.js和浏览器)

时间:2017-11-22 00:03:14      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:console   支持   open   ons   erro   window   style   closed   cti   

node.js服务端

先要安装ws模块的支持

npm install ws

 

服务端(server.js)

var gws;
var WebSocketServer = require(‘ws‘).Server,
    wss = new WebSocketServer({ port: 9000 });
wss.on(‘connection‘, function (ws) {
    gws = ws;
    console.log(‘client connected‘);
    ws.on(‘message‘, function (message) {
        console.log(message);
        setInterval(show,5000);//每隔5秒 服务端向浏览器 推送消息

    });
});

function show()
{
    gws.send(1122);
}

 

shell> node server.js

 

浏览器客户端

<script>
    if (window.WebSocket)
    {
        console.log("支持");
    }else
    {
        console.log("不支持");
    }
    var ws = new WebSocket(ws://localhost:9000);

    ws.onopen = function()

        {  console.log("open");

            ws.send("hello");

        };

    ws.onmessage = function(evt)

    {

        console.log(evt.data)

    };

    ws.onclose = function(evt)

    {

        console.log("WebSocketClosed!");

    };

    ws.onerror = function(evt)

    {

        console.log("WebSocketError!");

    };


</script>

 

我写的websocket推送例子,每隔5秒服务器向客户端浏览器发送消息(node.js和浏览器)

标签:console   支持   open   ons   erro   window   style   closed   cti   

原文地址:http://www.cnblogs.com/fps2tao/p/7875669.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!