如何将服务器上的传入消息路由到Socket.io中的html页面

时间:2017-05-26 07:54:10

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

基本上,我正在尝试将服务器端口上的传入数据显示到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");

1 个答案:

答案 0 :(得分:0)

您提供的代码不是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)
})
相关问题