nodeJs+socket.io

一、先安裝npm和nodejavascript

二、安裝socket.iohtml

npm install socket.io

三、htmljava

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

四、jsnode

/**
 * 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);
    });
});

五、啓動server.jsnpm

node server.js

六、其他api參考api

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息