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參考