3

socketio命名空间和房间设置

 2 years ago
source link: https://blog.p2hp.com/archives/9194
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

1.命名空间

分隔来最大程度地减少资源(TCP连接)的数量
客户端

		var qq = io.connect('http://localhost:3000/qq');
		  qq.on('connect', function() {
			  console.log("连接成功")
		  })
		  qq.on('news', function(data) {
			  console.log(data)
		  })
		  
		  var wx = io('http://localhost:3000/wx');
		  wx.on('connect', function() {
		  			  console.log("连接成功")
		  })
		  wx.on('news', function(data) {
		  			  console.log(data)
		  })

服务器
io.of( “/路径” )

 	socketio.io = require('socket.io')(server);
    var io = socketio.io;

	var qq = io.of("/qq");
    qq.on('connection', function(socket) {
        qq.emit('news', {hello: 'qq'})
    })
    var wx = io.of("/wx");
    wx.on('connection', function(socket) {
        wx.emit('news', {hello: 'wx'})
    })

2.加入房间群聊

可以join加入房间和leave离开房间。
客户端

	var con = io.connect('http://localhost:3000');
		  con.on('connect', function() {
			  console.log('连接成功')
		  })
		  con.emit('joinRoom',{
			  room: 'room',
			  content: '进入房间'
		  })
		  con.on('roomEvent', function(data) {
			  console.log(data)
		  })
		  function send() {
			  con.emit('sendMsg', {
			  room: 'room',
			  content: '群发消息'
			})
		}
		  

服务器socket.join(data.room); socket.to(data.room).emit(‘roomEvent’, data)

io.on('connection', function(socket) {
        socket.on('joinRoom', function(data) {
            console.log(data)
            socket.join(data.room);
            
        })
        socket.on('sendMsg', function(data) {
            socket.to(data.room).emit('roomEvent', data)
        })
    })

3.一对一发消息, 根据id发消息

			var con = io('http://localhost:3000');
			con.on('addUser', function(data) {
				console.log(data);//获取广播的信息
			})
			function send(toId) {
			con.emit('sendMsg', { fromid: con.id, toid: toId, msg: '客户端1'});
			}
			con.on('revMsg', function(data) {
				console.log(data);
				document.querySelector("h2").innerHTML = JSON.stringify(data);
			});
io.on('connection', function(socket) {
		io.sockets.emit('addUser', {
            id: socket.id,
            content: '广播有新用户加入'
        })
        socket.on('sendMsg', function(data) { //监听
            console.log(data);
            socket.to(data.toid).emit('revMsg', data)//发送对应id的客户端
        })
    })




Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK