NodeJS 如何使用express和socket.io通过rest API发送消息

deikduxw  于 2023-01-16  发布在  Node.js
关注(0)|答案(2)|浏览(126)

我有一个聊天应用程序,我试图让用户选择从一个url(rest API)发送消息。这个消息应该发送到其他客户端连接到套接字。这里是一个代码小。这是一个nodeJs应用程序。
用户A和B在一个房间中。用户C希望从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);
q8l4jmvw

q8l4jmvw1#

这可以简单地按如下方式完成。

// 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}`);
});

客户

const handlePress = () => {
    axios.get(`http://localhost:9723/users`).then(data => {
      console.log(data.data);
    });
  };

注意:此客户端只能通过express API发送到其他客户端。您可以将任何所需内容从服务器发送回客户端。如果您有www.example.com聊天应用程序,socket.io并且您希望在客户端没有socket.io库的情况下发送消息,则此功能非常有用

ve7v8dk2

ve7v8dk22#

答案是,REST是一种API架构模式,我们不能在WebSocket上使用REST。但是,HTTP和FTP是协议,我们可以在这些协议上使用WebSocket。好问题。

相关问题