• nodeJs+socket.io


    1、先安装npm和node

    2、安装socket.io

    npm install socket.io

    3、html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Ssocket</title>
        <script src="http://localhost:8088/socket.io/socket.io.js"></script>
    </head>
    
    <body>
    <div></div>
    <input type="text"/>
    <button>button</button>
    <script type="text/javascript">
        var input = document.getElementsByTagName("input")[0];
        var button = document.getElementsByTagName("button")[0];
        var div = document.getElementsByTagName("div")[0];
        var socket = io.connect('http://localhost:8088');
        var data;
        socket.on('news', function (data) {
            div.innerHTML=data.my;
            console.log(data);
        });
        button.onclick=function(){
            socket.emit('my other event', { my: input.value });
        };
    </script>
    
    </body>
    </html>
    

    4、js

    /**
     * Created by zcwl123 on 2017/5/9.
     */
    var app = require('http').createServer(handler),
        io = require('socket.io').listen(app),
        fs = require('fs')
    
    app.listen(8088);
    io.set('log level', 1);//将socket.io中的debug信息关闭
    
    function handler (req, res) {
        fs.readFile(__dirname + '/index.html',function (err, data) {
            if (err) {
                res.writeHead(500);
                return res.end('Error loading index.html');
            }
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end(data);
        });
    }
    
    io.sockets.on('connection', function (socket) {
        socket.emit('news', { hello: 'world' });
        socket.on('my other event', function (data) {
            io.sockets.emit('news', data);
            console.log(data);
            console.log(1);
        });
    });
    

    5、启动server.js

    node server.js

    6、其余api参考

  • 相关阅读:
    hdu 1712(分组背包)
    hdu 3033(好题,分组背包)
    阶乘除法(很久之前的一道题,感觉挺好的,遂记录之)
    hdu 1559(最大子矩阵)
    hdu 1080(LCS变形)
    POJ 3458 Colour Sequence
    HUST 1599 Multiple
    HDU 3903 Trigonometric Function
    HUST 1605 Gene recombination
    UVA 11551 Experienced Endeavour
  • 原文地址:https://www.cnblogs.com/huangqiming/p/6831728.html
Copyright © 2020-2023  润新知