該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
});
});
});
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
});
});
});
所以基本上你說我發送一條消息通過通道'gameId'到達服務器,然後服務器工作ks,那我對嗎?到目前爲止,客戶之間沒有「溝通」,那基本上沒有「渠道」。 好吧,謝謝,我不得不重組我的整個應用程序。 – Masiar