socket.io如何给指定的客户端发送自定义事件?
发布于 11 年前 作者 blanche 10130 次浏览 最后一次编辑是 8 年前

如题。。另外想问一下哪里有socket.io的教程啊,感觉socket.io官网上的例子太简单,而且有些写法似乎有问题。

2 回复

缓存每个Client就行了

之前試寫的聊天, 主要是io.sockets.emit(‘updatechat’, socket.username, message);

io.sockets.on ( ‘connection’, function(socket) { // when the client emits ‘sendchat’, this listens and executes socket.on ( ‘sendchat’, function(message) { //socket.broadcast.emit //( // ‘updatechat’, { Content: message } //);

			io.sockets.emit('updatechat', socket.username, message);
		}
	);
	
	// when the client emits 'adduser', this listens and executes
	socket.on
	(
		'adduser', function(username)
		{
			// we store the username in the socket session for this client
			socket.username = username;
			// add the client's username to the global list
			usernames[username] = username;
			// echo to client they've connected
			socket.emit('updatechat', 'SERVER', 'you have connected');
			// echo globally (all clients) that a person has connected
			socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
			// update the list of users in chat, client-side
			io.sockets.emit('updateusers', usernames);
		}
	);
	
	// when the user disconnects.. perform this
	socket.on
	(
		'disconnect', function()
		{
			// remove the username from global usernames list
			delete usernames[socket.username];
			// update list of users in chat, client-side
			io.sockets.emit('updateusers', usernames);
			// echo globally that this client has left
			socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
		}
	);
}

);

回到顶部