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

NodeJS实现WebSocket

时间:2017-11-24 16:57:50      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:disco   user   document   sage   charset   meta   type   use   websocket   

npm install --save express
npm install --save socket.io

服务器端代码:

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‘);
});

客户端代码

<!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>

 

NodeJS实现WebSocket

标签:disco   user   document   sage   charset   meta   type   use   websocket   

原文地址:http://www.cnblogs.com/white0710/p/7890891.html

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