Aller au contenu principal
Latest blog post (July 25, 2024): npm package provenance.
Ceci est la documentation de Socket.IO 3.x, qui n'est plus activement maintenue.
Pour une documentation à jour, consultez la dernière version (4.x).
Version: 3.x

Application structure

Registering event handlers

You will find below two suggestions on how to register your event handlers.

Please note that these are merely suggestions and not strict guidelines that you must follow. Please adapt it to your own liking!

Each file registers its own event handlers

Here, the entrypoint is kept tidy, but the event listeners may be less discoverable (though strong naming convention/ctrl+f will help).

index.js

const httpServer =require("http").createServer();
const io =require("socket.io")(httpServer);

const registerOrderHandlers =require("./orderHandler");
const registerUserHandlers =require("./userHandler");

constonConnection=(socket)=>{
registerOrderHandlers(io, socket);
registerUserHandlers(io, socket);
}

io.on("connection", onConnection);

orderHandler.js

module.exports=(io, socket)=>{
constcreateOrder=(payload)=>{
// ...
}

constreadOrder=(orderId, callback)=>{
// ...
}

socket.on("order:create", createOrder);
socket.on("order:read", readOrder);
}

All event handlers are registered in the index.js file

Here, each event name is located in the same place, which is great for discoverability, but could get out of hand in a medium/big application.

index.js

const httpServer =require("http").createServer();
const io =require("socket.io")(httpServer);

const{ createOrder, readOrder }=require("./orderHandler")(io);
const{ updatePassword }=require("./userHandler")(io);

constonConnection=(socket)=>{
socket.on("order:create", createOrder);
socket.on("order:read", readOrder);

socket.on("user:update-password", updatePassword);
}

io.on("connection", onConnection);

orderHandler.js

module.exports=(io)=>{
constcreateOrder=function(payload){
const socket =this;// hence the 'function' above, as an arrow function will not work
// ...
};

constreadOrder=function(orderId, callback){
// ...
};

return{
createOrder,
readOrder
}
}

AltStyle によって変換されたページ (->オリジナル) /