Socket.io应用实例

2016/12/12
项目用到了socket.io做了同步教学
自己就总结下,发现和swoole和workerman差不多
基于高性能异步io
基于nodejs
下载很简单 直接去socket.io 下载即可 github
长连接的好处就是可以做很多好玩的应用
以后有机会希望可以接触下智能家居

君不见黄河之水天上来,有朝望尽天涯路

安装


能用yum的就yum 特殊需要编译其他扩展的就源码编译
安装首推rpm包

yum install nodejs npm
npm install socket.io


服务端

io.on('connection',function(socket));

监听客户端连接,回调函数会传递本次连接的socket

io.sockets.emit('String',data);

给所有客户端广播消息

io.sockets.socket(socketid).emit('String', data);

给指定的客户端发送消息

socket.on('String',function(data));

监听客户端发送的信息

socket.emit('String', data);

给该socket的客户端发送消息

广播消息

//给除了自己以外的客户端广播消息
socket.broadcast.emit("msg",{data:"hello,everyone"}); 
//给所有客户端广播消息
io.sockets.emit("msg",{data:"hello,all"});

分组

socket.on('group1', function (data) {
    socket.join('group1');
});
socket.on('group2',function(data){
    socket.join('group2');
});

踢出分组

socket.leave(data.room);

客户端发送

// 发送到当前请求套接字客户端
socket.emit('message', "this is a test");

// 发送给所有客户端,除了发件人客户端
socket.broadcast.emit('message', "this is a test");

// 发送到所有客户在游戏分组的房间,除了发件人客户端
socket.broadcast.to('game').emit('message', 'nice game');

// 发送给所有客户端,包括发件人客户端
io.sockets.emit('message', "this is a test");

// 发送到所有客户在游戏分组的房间,不包括发件人客户端
io.sockets.in('game').emit('message', 'cool game');

// 发送个个人当前客户端
io.sockets.socket(socketid).emit('message', 'for your eyes only');

客户端socket.on()监听的事件

connect:连接成功
connecting:正在连接
disconnect:断开连接
connect_failed:连接失败
error:错误发生,并且无法被其他事件类型所处理
message:同服务器端message事件
anything:同服务器端anything事件
reconnect_failed:重连失败
reconnect:成功重连
reconnecting:正在重连
当 第一次连接时,事件触发顺序为:connecting->connect;当失去连接时,事件触发顺序 为:disconnect->reconnecting(可能进行多 次)->connecting->reconnect->connect

实战代码

这个服务器的代码实现了页面同步 单用户控制多用户

var app = require('express')();
var path = require('path');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var socketList = {};
//io.set('log level', 1);

app.get('/', function(req, res){
	res.sendFile(__dirname + '/index.html');
});

io.sockets.on('connection', function (socket){
    console.log('connection........');
    socket.on('room', function (nn) {
		
		try {
            var roomId = nn.split('|')[0];
			var isTeacher = nn.split('|')[1];
			var studentId = nn.split('|')[2];
        }catch(e){return false;}
	
        socket.join(roomId);
        
	
    	if(socketList[roomId] == undefined) {
            socketList[roomId] = {};
            socketList[roomId] ['roomnum'] = roomId;
        }
	
        if(isTeacher == 'false') {
			
            socketList[roomId] [studentId] = {};
            socketList[roomId] [studentId]['socketid'] = socket.id;
            socketList[roomId] [studentId]['isonline'] = 'true';
            socketList[roomId] [studentId]['locked'] = 'true';
			socketList[roomId] [studentId]['sid'] = studentId;
        }
		
        io.sockets.in(roomId).emit('request_list_ans',socketList[roomId] );
    
        socket.on('send_message', function (msg){
            var msg1 = eval('(' + msg + ')');//json数据 序列化成js对象
			
			var user_data_info = msg1.user_data;
			
			if (user_data_info != '' &&  user_data_info != 'undefined') {
				
				try {
					var user_id = user_data_info.split('|')[2];
				}catch(e){return false;}
				
				if(user_id != '' &&  user_id != 'undefined') {
				
					try {
						io.to(socketList[roomId] [user_id]['socketid'] ).emit('send_message',msg );
					}catch(e){return false;}
				
				} else {
					io.sockets.in(roomId).emit('send_message', msg);
				}
			}
			
            
        });

        socket.on('request_list', function (msg){
            var roomId = msg.split('|')[0];
            
            io.to(socket.id).emit('request_list_ans',socketList[roomId] );
        });

        socket.on('operate_all', function (msg){
			console.log(1);
            var roomId = msg.split('|')[0];
            var lockInfo = msg.split('|')[1];
            
            for(var key in socketList[roomId]){
                console.log('key:' + key);
                if(key!='roomnum')
                socketList[roomId][key]['locked']=''+lockInfo;
            }
            io.to(socket.id).emit('operate_all_ans','ok' );
            io.sockets.in(roomId).emit('send_lockInfo', lockInfo);
			io.sockets.emit("teacher_is_lock_all",lockInfo);
        });

        socket.on('operate_spec', function (msg){
			
            var roomId = msg.split('|')[0];
            var studentId = msg.split('|')[1];
            var lockInfo = msg.split('|')[2];
			
			if (socketList[roomId] [studentId]) { //当前用户存在在发送锁定信息
				console.log(lockInfo);
				socketList[roomId] [studentId]['locked'] = lockInfo;
				io.to(socket.id).emit('operate_spec_ans','ok' );
				io.to(socketList[roomId] [studentId]['socketid'] ).emit('send_lockInfo',lockInfo );
			}
			var con = studentId+'|'+lockInfo;
			io.sockets.emit("teacher_is_lock",con);
        });

    	socket.on('client_status', function (msg){
    	    var roomId = msg.split('|')[0];
            var studentId = msg.split('|')[1];
            var onlineInfo = msg.split('|')[2];
    	    socketList[roomId] [studentId]['isonline'] = ''+onlineInfo;
    	    
    	    io.sockets.in(roomId).emit('request_list_ans',socketList[roomId] );
    	});
		
		socket.on("disconnect",function(){
			io.sockets.in(roomId).emit('request_list_ans','001' );//断开链接进行减法运算
			try {
				io.sockets.in(roomId).emit('edit_head',socketList[roomId] [studentId]['sid'] );//
			}catch(e){return false;}
			
			delete socketList[roomId] [studentId];
		});

    });

});



http.listen(8091, function(){
	console.log('listening on *:8091');
});


个人随笔

安静的等待,你若盛开,蝴蝶自来

承接高质量 网站开发 app开发 如有需要请点击About联系

@承鹏辉