node(websocket)

來源:互聯網
上載者:User

標籤:

websocket原本是html5下實現長連結的一個特性,當前已被眾多瀏覽器支援。

在websocket協議中,首先通過http交換一次握手,明確將協議升級至websocket。同時建立一個TCP通道,以frame幀的方式交換資料。

在node環境下準系統實現如下:

首先npm install socket.io

1、app.js,初始化socket.io

var srv = http.createServer(app).listen(app.get(‘port‘), function(){  console.log(‘Express server listening on port ‘ + app.get(‘port‘));});var io     = require(‘socket.io‘).listen(srv);server.initServer(io);

2、server.js實現伺服器端代碼

exports.initServer = function(io){        io.on(‘connection‘,function(socket){        console.log(‘connection‘);        socket.on(‘disconnect‘,function(msg){            console.log(‘disconnect‘);        });                socket.on(‘msg1‘,function(msg){            console.log(msg);                        socket.emit(‘back‘,{key:‘fredric&sinny‘});        });        });    }

3、用戶端代碼

<!DOCTYPE html><html><head><script src = "socket.io.js"></script><script>    var socket = io.connect(‘http://localhost:3000‘);        function sendmsg(){               console.log(‘start sendmsg‘);        socket.emit(‘msg1‘,{key:‘fredric‘});    }        socket.on(‘back‘,function(msg){        alert(msg.key);    });    </script></head><body><button type="button" onclick=‘sendmsg()‘>Click Me!</button></body></html>

瀏覽器端調試網路介面如下:

 

node(websocket)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.