I have a chat app that I am trying to allow users an option to send a message from a url (rest api). This message should be send to other clients connect to the socket. Here is a little of the code. This is a nodeJs app.
User A & B are in a room. User C wants to send them a message from Rest Api http://localhost:3000/sendMessage?message=hello&roomId=123
import express from "express";
import { createServer } from "http";
import { Server } from "socket.io";
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
/* options */
});
io.on("connection", (socket) => {
app.get("/sendMessage", function (req, res) {
res.send("Message sent");
// This will send message to other clients when this endpoint is called
io.to("devices-in-this-room").emit("message", req.body.content);
});
});
httpServer.listen(3000);
CodePudding user response:
This can be done simply as follows.
// The Server
import express from 'express';
import { createServer } from 'http';
import { Server } from 'socket.io';
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
cors: {
origin: '*'
}
});
const port = process.env.PORT || 9723;
// If you are using typescript include this declare block
// Used to extend express Request (req) type definition
declare global {
namespace Express {
interface Request {
admin: any;
io: Server; // Server is coming from the import
}
}
}
io.on('connection', (socket) => {
// ...
});
// Allows you to send emits from express
app.use(function (request, response, next) {
request.io = io;
next();
});
// This is how you can use express to emit to other sockets
app.get('/users', (req, res) => {
// emit to other sockets or room (all socket.io events supported)
req.io.timeout(5000).emit("tester", (err, responses) => {
if (err) {
// some clients did not acknowledge the event in the given delay
} else {
res.json(responses) // depending on your data
}
});
// send api data, route, info , etc to web client, axios, etc
res.send('Users Page');
});
httpServer.listen(port, () => {
console.log(`listening on *:${port}`);
});
The Client
const handlePress = () => {
axios.get(`http://localhost:9723/users`).then(data => {
console.log(data.data);
});
};
Note: this client can only emit to other clients via the express api. You can send whatever you want back to the client from the server. This can be useful if you have chat app with socket.io and you want to send messages if client does not have the socket.io library
CodePudding user response:
The answer is no, REST is an API architecture pattern, we can't use REST over WebSocket. But, HTTP and FTP are protocols, we can use WebSocket over those protocols. Nice Question.