标签:
项目代码下载:点击这里
/* 封装socket.io,为了获取server以便监听. 2016年8月8日10:28:24 */ var socketio = {}; var socket_io = require('socket.io'); //获取io socketio.getSocketio = function(server){ var io = socket_io.listen(server); }; module.exports = socketio;
/* 封装socket.io,为了获取server以便监听. 2016年8月8日10:28:24 */ var socketio = {}; var socket_io = require('socket.io'); //获取io socketio.getSocketio = function(server){ var io = socket_io.listen(server); io.sockets.on('connection', function (socket) { console.log('连接成功'); socket.on('click1',function(){ console.log('监听点击事件'); var datas = [1,2,3,4,5]; socket.emit('click2', {datas: datas}); socket.broadcast.emit('click2', {datas: datas}); }) }) }; module.exports = socketio;-- index.ejs
<!DOCTYPE html> <html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css' /> <!--socket.io--> <script type="text/javascript" src="http://cdn.staticfile.org/socket.io/1.3.7/socket.io.js"></script> </head> <body> <h1><%= title %></h1> <p>Welcome to <%= title %></p> <button onclick="a()">按钮</button> <ul id="ultext"> </ul> </body> <script type="text/javascript"> var socket = io(); function a(){ socket.emit('click1'); } //监听click2事件 socket.on('click2', function(data){ var htmldatas = data.datas; var html = ''; for (var i = 0; i < htmldatas.length; i++) { var htmldata = htmldatas[i]; html += '<li>'+htmldata+'</li>'; } document.getElementById('ultext').innerHTML = html; }) </script> </html>
标签:
原文地址:http://blog.csdn.net/zzwwjjdj1/article/details/52149438