[英]connecting two clients with socket.io through node.js
我试图让两个客户端(玩家)通过socket.io相互联系(交换示例字符串)。 我在客户端上有这个代码(gameId在代码中定义):
var chat = io.connect('http://localhost/play');
chat.emit(gameId+"", {
guess: "ciao"
});
chat.on(gameId+"", function (data) {
alert(data.guess);
});
虽然在服务器上我有这个(这是我做的第一件事,当然不是路由)
var messageExchange = io
.of('/play')
.on('connection', function (socket) {
socket.emit('message', {
test: 'mex'
});
});
基本上我创建了频道,然后当用户连接时,他们使用频道交换国王“gameId”的消息,只有他们两个都可以阅读(使用on.(gameId+"" ...
东西。我的问题是那个当玩家连接(第一个,然后是另一个)时,连接的第一个应该警告收到的数据(因为第二个连接发出的消息)。你们有谁知道为什么没有发生这种情况?
谢谢。
socket.io服务器应该像一个中间人。 它可以从客户端接收消息并向客户端发送消息。 默认情况下,它不会充当“通道”,除非您有服务器将消息从客户端中继到其他客户端。
关于他们网站上常见用途的很多好消息, http://socket.io和他们的回购, https://github.com/LearnBoost/socket.io
聊天客户端的一个简单示例可能是这样的:
var chat = io.connect("/play");
var channel = "ciao";
// When we connect to the server, join channel "ciao"
chat.on("connect", function () {
chat.emit("joinChannel", {
channel: channel
});
});
// When we receive a message from the server, alert it
// But only if they're in our channel
chat.on("message", function (data) {
if (data.channel == channel) {
alert(data.message);
}
});
// Send a message!
chat.emit("message", { message: "hola" });
虽然服务器可以这样做:
var messageExchange = io
.of('/play')
.on('connection', function (socket) {
// Set the initial channel for the socket
// Just like you set the property of any
// other object in javascript
socket.channel = "";
// When the client joins a channel, save it to the socket
socket.on("joinChannel", function (data) {
socket.channel = data.channel;
});
// When the client sends a message...
socket.on("message", function (data) {
// ...emit a "message" event to every other socket
socket.broadcast.emit("message", {
channel: socket.channel,
message: data.message
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.