這次給大家帶來NodeJS怎么實現WebSocket功能,NodeJS實現WebSocket功能的注意事項有哪些,下面就是實戰案例,一起來看一下。
我們基於express和socket.io開發,首先我們需要安裝以下包
1 2 |
npm install --save express
npm install --save socket.io
|
服務器端代碼:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var app = require ( 'express' )();
var http = require ( 'http' ).Server(app);
var io = require ( 'socket.io' )(http);
app.get( '/' , function (req, res){
res.send( '<h1>Welcome Realtime Server</h1>' );
});
io.on( 'connection' , function (socket){
console.log( 'a user connected' );
socket.on( "disconnect" , function () {
console.log( "a user go out" );
});
socket.on( "message" , function (obj) {
io.emit( "message" , obj);
});
});
http.listen(3000, function (){
console.log( 'listening on *:3000' );
});
|
客戶端代碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<!DOCTYPE html>
<html lang= "en" >
<head>
<meta charset= "UTF-8" >
<title>Document</title>
<script src= "http://127.0.0.1:3000/socket.io/socket.io.js" ></script>
</head>
<body>
<ul id= "message" ></ul>
<script>
socket = io.connect( 'ws://127.0.0.1:3000' );
socket.emit( "message" , { "name" : navigator.userAgent, "msg" : "hello world" });
socket.on( "message" , function (obj) {
console.log(obj);
});
</script>
</body>
</html>
|
一個控制台版的聊天室做好了(^o^)/~
相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
推薦閱讀:
Immutable.js怎樣實現撤銷重做效果
Vuex的mutations與actions使用詳解
以上就是NodeJS怎么實現WebSocket功能的詳細內容,更多請關注php中文網其它相關文章!