【问题标题】:How do I route incoming messages on server to an html page in Socket.io如何将服务器上的传入消息路由到 Socket.io 中的 html 页面
【发布时间】:2017-05-26 07:54:10
【问题描述】:

基本上,我试图将服务器端口上的传入数据显示到 HTML 网页。此代码显示传入消息以及加入或离开的人,但在控制台窗口上,我试图在网页上显示这些消息。请帮忙。谢谢。

服务器端代码-

   // Load the TCP Library
   net = require('net');

    // Keep track of the chat clients
   var clients = [];

   // Start a TCP Server
   net.createServer(function (socket) {

   // Identify this client
   socket.name = socket.remoteAddress + ":" + socket.remotePort 

  // Put this new client in the list
  clients.push(socket);

  // Send a nice welcome message and announce
  socket.write("Welcome " + socket.name + "\n");
  broadcast(socket.name + " joined \n", socket);

  // Handle incoming messages from clients.
  socket.on('data', function (data) {
  broadcast(socket.name + "> " + data, socket);
  });

  // Remove the client from the list when it leaves
  socket.on('end', function () {
  clients.splice(clients.indexOf(socket), 1);
  broadcast(socket.name + " left the chat.\n");
  });

  // Send a message to all clients
  function broadcast(message, sender) {
  clients.forEach(function (client) {
    // Don't want to send it to sender
    if (client === sender) return;
    client.write(message);
  });
  // Log it to the server output too
  process.stdout.write(message)
  }

  }).listen(3000);

   // Put a friendly message on the terminal of the server.
 console.log("server running at port 3000\n");

【问题讨论】:

    标签: node.js sockets socket.io tcp-ip


    【解决方案1】:

    您提供的代码不是socket.io,它类似于tcp chat。

    只要关注these instructions你就会明白

    更新

    目的:通过tcp-ip发送数据,通过http实时获取。

    要实现这一点,我们必须经过几个步骤:

    • 创建 tcp 服务器(你已经有了)
    • 创建socket.io服务器(如果你不需要实时,如果页面刷新就可以获取新数据——通常的http服务器就足够了)
    • 在两台服务器之间创建共享内存(或数据库存储作为选项)

    我会写伪js代码,只是为了让你了解如何实现它:

    const app = require('express')()
    const MESSAGES = []
    app.get('/', (req, res) => {
       res.send(MESSAGES)
    })
    app.listen(3000, ()=> console.log('server started'))
    
    // and your code.. I won't repeat just a sample
    // Handle incoming messages from clients.
    socket.on('data', function (data) {
      MESSAGES.push(data)
      broadcast(socket.name + "> " + data, socket)
    })
    

    【讨论】:

    • 嗨,感谢您的回复。我有一个使用 TCP-IP 与服务器通信的设备。该设备将其数据发送到给定的 IP 和端口,我上面的服务器端代码也显示接收到的数据在控制台窗口中,我发现很难在 index.html 页面上显示它。我尝试了很多示例,但只有通过浏览器传递所有显示消息
    • 好的,你想用那个设备在网络上看吗?
    • 是的,我希望该设备在网络上看到,就像该网页用于监控来自该设备的数据一样。这可能吗?
    • 是的,我想要实时数据,但很抱歉我仍然觉得您的答案难以理解,您能否详细解释一下。为什么我应该使用两台服务器以及如何使用 res.send (MESSAGES)`语句用于在网络上显示
    • 1 个服务器提供 tcp-ip 连接,第 2 个提供 http 连接。我建议你使用通常的网络,当你得到它时,使用 socket.io 切换到实时。就你运行而言,在浏览器中输入:localhost:3000,在机器上服务器正在运行,而不是设备上。要在设备上运行,您必须部署它。
    猜你喜欢
    • 2014-07-10
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    • 2021-12-07
    • 2014-02-28
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    相关资源
    最近更新 更多