zoukankan      html  css  js  c++  java
  • 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参考

  • 相关阅读:
    海量数据与布隆过滤
    Flink History Job
    golang and intellij
    maven中如何得到父工程的位置
    maven中进行go的编译
    hbase表的写入
    Storm之tickTuple
    storm-kafka版本不匹配的问题
    (17)zabbix自定义用户key与参数User parameters
    (16)zabbix history trends历史与趋势数据详解
  • 原文地址:https://www.cnblogs.com/huangqiming/p/6831728.html
Copyright © 2011-2022 走看看