メインコンテンツにスキップ
バージョン: 4.x

Emit チートシート

{/* SVGアイコンは翻訳不要 */}注意

以下のイベント名は予約済みであり、アプリケーションで使用しないでください。

  • connect
  • connect_error
  • disconnect
  • disconnecting
  • newListener
  • removeListener
// BAD, will throw an error
socket.emit("disconnecting");

サーバー

単一クライアント

基本的な emit

io.on("connection", (socket) => {
socket.emit("hello", 1, "2", { 3: "4", 5: Buffer.from([6]) });
});

確認応答

io.on("connection", (socket) => {
socket.emit("hello", "world", (arg1, arg2, arg3) => {
// ...
});
});

確認応答とタイムアウト

io.on("connection", (socket) => {
socket.timeout(5000).emit("hello", "world", (err, arg1, arg2, arg3) => {
if (err) {
// the client did not acknowledge the event in the given delay
} else {
// ...
}
});
});

ブロードキャスト

接続されているすべてのクライアントに

io.emit("hello");

送信者を除く

io.on("connection", (socket) => {
socket.broadcast.emit("hello");
});

確認応答

io.timeout(5000).emit("hello", "world", (err, responses) => {
if (err) {
// some clients did not acknowledge the event in the given delay
} else {
console.log(responses); // one response per client
}
});

ルーム内

  • "my room"という名前のルーム内のすべての接続済みクライアントに
io.to("my room").emit("hello");
  • "my room"という名前のルーム内にいないすべての接続済みクライアントに
io.except("my room").emit("hello");
  • 複数の条件付き
io.to("room1").to(["room2", "room3"]).except("room4").emit("hello");

名前空間内

io.of("/my-namespace").emit("hello");
{/* SVGアイコンは翻訳不要 */}ヒント

修飾子は絶対に連結できます

io.of("/my-namespace").on("connection", (socket) => {
socket
.timeout(5000)
.to("room1")
.to(["room2", "room3"])
.except("room4")
.emit("hello", (err, responses) => {
// ...
});
});

これは、接続されているすべてのクライアントに「hello」イベントを送信します

  • my-namespace という名前の名前空間内
  • room1room2room3 という名前のルームの少なくとも1つに属し、room4 には属さない
  • 送信者を除く

そして、次の5秒で確認応答を期待します。

サーバー間

基本的な emit

io.serverSideEmit("hello", "world");

受信側

io.on("hello", (value) => {
console.log(value); // "world"
});

確認応答

io.serverSideEmit("hello", "world", (err, responses) => {
if (err) {
// some servers did not acknowledge the event in the given delay
} else {
console.log(responses); // one response per server (except the current one)
}
});

受信側

io.on("hello", (value, callback) => {
console.log(value); // "world"
callback("hi");
});

クライアント

基本的な emit

socket.emit("hello", 1, "2", { 3: "4", 5: Uint8Array.from([6]) });

確認応答

socket.emit("hello", "world", (arg1, arg2, arg3) => {
// ...
});

確認応答とタイムアウト

socket.timeout(5000).emit("hello", "world", (err, arg1, arg2, arg3) => {
if (err) {
// the server did not acknowledge the event in the given delay
} else {
// ...
}
});