74 lines
No EOL
1.8 KiB
Markdown
74 lines
No EOL
1.8 KiB
Markdown
socket.io
|
|
|
|
- Using with http module
|
|
```js
|
|
const PORT = process.env.PORT || 8080;
|
|
|
|
const httpServer = require("http").createServer();
|
|
const socketIO = require("socket.io");
|
|
|
|
const io = socketIO(httpServer, {
|
|
cors: { origin: "*" },
|
|
});
|
|
|
|
// when client connects to the server
|
|
io.on("connection", (socket) => {
|
|
console.log(`user connected ${socket.id}`);
|
|
io.emit("requestKey");
|
|
|
|
// when listening to custom event named 'message'
|
|
socket.on("message", (msgObjs) => {
|
|
// here using socket.broadcast.emit will send message to all client except the one who originally sent to server
|
|
|
|
for (let msgObj of msgObjs) {
|
|
const id = msgObj.sid;
|
|
io.to(id).emit("message", msgObj.message, socket.id);
|
|
}
|
|
|
|
// socket.broadcast.emit(
|
|
// "message",
|
|
// `${socket.id.substr(0, 2)} said ${message}`
|
|
// );
|
|
|
|
// to send to all including OP, use io.emit
|
|
// and for particular client use
|
|
// io.to(socket.id). emit("event", data);
|
|
});
|
|
```
|
|
|
|
|
|
|
|
- Using with express
|
|
```js
|
|
const express = require('express');
|
|
const app = express();
|
|
const socketIO = require('socket.io');
|
|
|
|
const PORT = process.env.PORT || 8080;
|
|
const keys = [];
|
|
|
|
// Serve your application on a specific route using Express
|
|
app.get('/', (req, res) => {
|
|
res.sendFile(__dirname + '/index.html'); // Replace 'index.html' with your HTML file
|
|
});
|
|
|
|
// Create the HTTP server using Express
|
|
const server = app.listen(PORT, () => {
|
|
console.log(`Server is running on port ${PORT}`);
|
|
});
|
|
|
|
// Initialize Socket.io by passing the HTTP server instance
|
|
const io = socketIO(server, {
|
|
cors: { origin: "*" },
|
|
});
|
|
|
|
// Socket.io logic
|
|
io.on("connection", (socket) => {
|
|
console.log(`User connected: ${socket.id}`);
|
|
io.emit("requestKey");
|
|
|
|
// ... (rest of your Socket.io logic)
|
|
});
|
|
|
|
```
|
|
|