zoukankan      html  css  js  c++  java
  • NodeJS实现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>
  • 相关阅读:
    Comet OJ
    AtCoder Grand Contest 002题解
    AtCoder Grand Contest 001 题解
    线性基求交
    2019牛客暑期多校训练营(第四场)题解
    AtCoder Grand Contest 036题解
    计算几何 val.2
    计算几何 val.1
    模拟退火学习笔记
    动态点分治学习笔记
  • 原文地址:https://www.cnblogs.com/white0710/p/7890891.html
Copyright © 2011-2022 走看看