【发布时间】: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