[英]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.