NodeJS - Socket.IO

服务端:

io.sockets.on('connection', function (socket) {
	// 向当前客户端发送事件
	// 发送给单个用户
	socket.emit('message', "this is a test");
	
	// 发送给所有端,不包括发送端 
	// 广播(不包含当前客户端)
	socket.broadcast.emit('message', "hello,everyone");
	
	// 发送给所有端,包括发送端 
	// 广播(包含当前客户端)
	io.sockets.emit('message', "hello,all");
	
	// 发送给所有在room1房间中的端,不包括发送端 
	// 在房间广播(不包含当前客户端)
	socket.broadcast.to('room1').emit('message', 'nice game');
	
	// 发送给所有在room1房间中的端,包括发送端 
	// 在房间广播(包含当前客户端)
	io.sockets.in('room1').emit('message', 'cool game');
	// 发送给指定客户端(实现一)
	io.sockets.in(socket.id).emit('message', {data:"发送给指定客户端"});
	
	// 发送给指定客户端
	io.sockets.sockets[socketid].emit('message', 'for your eyes only');

	// 发送给当前连接的 socket 客户端
	io.emit('message', "this is a test");
 
	// 发送给指定客户端(实现二)
	io.sockets.connected[socket.id].emit('message',{data:"发送给指定客户端"});
});

知识点

io.on('connection', socket => {
	// 通过socket.handshake获得了用户请求信息
	console.info(socket.handshake);
	// 获取用户ip
	console.info(socket.handshake);
	// 获取socket id
	console.info(socket.id);
});

猜你喜欢

转载自blog.csdn.net/seaalan/article/details/85072622