如何将一个函数从服务器发送到客户端

huangapple go评论92阅读模式
英文:

How do i send a function from the server to the client

问题

我是新手学习在 NodeJS 和 ExpressJS 中进行 POST 请求。我尝试传递一个函数(而不是函数的结果),以便在客户端中调用它。我有这个监听器和这个 POST 请求(我试图制作一个 Discord 机器人的 Web 视图工具)。

服务器端

app.post("/dashboardstartup", jsonParser, (req, res) => {
    // authClient 是 Discord 客户端(Discord 机器人)

    if(authClient)
    {
        authClient.on("messageCreate", (message) => {
             // 一旦消息创建,始终发送消息
             res.json({
                 message
             })
             // 问题是,当我发送结果时,来自客户端的 fetch 请求停止了
        });
    }
})

客户端

// ...

await fetch("http://localhost:8080/dashboardstartup", {
     method: "POST",
     headers: {
         'Content-type': 'application/json'
     }

}).then(a=>a.json()).then(a=>{
   // 一旦接收到 fetch 响应,fetch 停止,客户端无法再监听消息

  console.log(a.messsage) // 输出 "Hello world!"
})

是否有更好的方法来实现这个,而不是使用 fetch 方法?

英文:

Im new to post requests in NodeJS & ExpressJS, Im trying to pass in a function (not the function's result) to get called in the client, I have this listener and this post request (Im trying to make a discord bot webview tool)

The Server-Side

app.post("/dashboardstartup", jsonParser, (req, res) => {
    // authClient is a discord client (Discord Bot)

    if(authClient)
    {
        authClient.on("messageCreate", (message) => {
             // always send the message once its created
             res.json({
                 message
             })
             // the problem is that when I send the result the fetch request from the client stops
        });
    }
})

The Client-Side

// ...

await fetch("http://localhost:8080/dashboardstartup", {
     method: "POST";
     headers: {
         'Content-type': 'application/json'
     }

}).then(a=>a.json()).then(a=>{
   // once the fetch response is received, the fetch stops and the client can't listen to messages anymore

  console.log(a.messsage) // prints out "Hello world!"
})

> And is there any better way to do this, than fetch method?

答案1

得分: 2

我理解您的目标是使用Node.js和ExpressJS创建一个实时通信渠道,使Discord机器人与客户端之间可以实时通信。尽管您尝试使用POST请求从服务器向客户端发送更新,但需要注意,由于其一次性请求-响应的特性,HTTP POST不适合实时通信。

为了实现实时更新,我建议使用WebSockets,因为它们提供了全双工通信,可以在服务器和客户端之间建立持续连接。

以下是您可以实施此功能的大致步骤:

在服务器端(使用ws库进行WebSocket通信):

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

// 模拟在Discord机器人中创建消息
function simulateMessageCreation() {
  return "Hello world!";
}

wss.on('connection', (ws) => {
  // 每当创建消息时,向客户端发送消息
  authClient.on("messageCreate", (message) => {
    const messageContent = simulateMessageCreation();
    ws.send(JSON.stringify({ message: messageContent }));
  });
});

在客户端端(在浏览器中使用WebSocket API):

const ws = new WebSocket("ws://localhost:8080");

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log(data.message); // 当创建新消息时打印出"Hello world!"
};

通过使用WebSockets,您可以在服务器和客户端之间建立持久连接,实现实时更新。这样,您的客户端应用程序将能够连续监听消息,而无需重复的HTTP请求。

在运行服务器之前,请记得使用npm安装所需的依赖项,例如ws库。

WebSockets是在Web应用程序中实现实时通信的强大工具,我鼓励您进一步探索它们的功能。

英文:

I understand your goal of creating a real-time communication channel between your Discord bot and the client using Node.js and ExpressJS. While you attempted to use a POST request to send updates from the server to the client, it's important to note that HTTP POST is not suitable for real-time communication due to its one-time request-response nature.

To achieve real-time updates, I recommend using WebSockets, as they provide full-duplex communication, making it possible to establish a continuous connection between the server and the client.

Here's an outline of how you can implement this:
On the server side (using ws library for WebSocket communication):

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

// Simulating message creation in your Discord bot
function simulateMessageCreation() {
 return "Hello world!";
}

wss.on('connection', (ws) => {
// Send a message to the client whenever a message is created
 authClient.on("messageCreate", (message) => {
   const messageContent = simulateMessageCreation();
   ws.send(JSON.stringify({ message: messageContent }));
 });
});

On the client side (using WebSocket API in the browser):

const ws = new WebSocket("ws://localhost:8080");

ws.onmessage = (event) => {
 const data = JSON.parse(event.data);
 console.log(data.message); // prints out "Hello world!" when a new 
message is created
};

By using WebSockets, you can establish a persistent connection between the server and the client, enabling real-time updates. This way, your client application will be able to listen for messages continuously without the need for repeated HTTP requests.

Remember to install the required dependencies, such as the ws library, using npm before running the server.

WebSockets are a powerful tool for enabling real-time communication in web applications, and I encourage you to explore their capabilities further.

答案2

得分: 0

你可以使用本地的response.write()方法。

response.json()方法来自Express.js包,并在发送响应后内部关闭连接。

以下是如何使用.write()的示例:

authClient.on("messageCreate", (message) => {
             // always send the message once its created
             res.write(JSON.stringify({ message }), 'utf8');
        });

它不会在您手动关闭连接之前关闭连接,客户端将继续监听消息。因此,请记住在authClient结束时结束响应:

authClient.on('close', () => res.end());
英文:

You can make use of the native response.write() method.

The response.json() method comes from the Express.js package and it internally closes the connection after sending the response.

Here's an example of how you can use .write():

authClient.on("messageCreate", (message) => {
             // always send the message once its created
             res.write(JSON.stringify({ message }), 'utf8');
        });

It doesn't close the connection until you manually do it and the client will keep listening for messages. So remember to end the response when authClient ends as well:

authClient.on('close', () => res.end());

huangapple
  • 本文由 发表于 2023年7月31日 20:52:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76803828.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定