是否可以通过 TCP 服务器使用 NodeJS 更新 HTML(内部HTML)?

Is it possible to update a HTML (innerHTML) with NodeJS over a TCP Server?

我不知道如何将我的数据从 tcp 服务器获取到 html 文件中。我想从 Java 应用程序向服务器发送消息。如果服务器收到消息,它应该用内容更新 HTML。 请求成功,但我不知道如何将数据传输到 Html 站点,我不知道如何启动该站点。

抱歉这个问题,我是 NodeJS 的新手

那是我的 server.js:

var net = require('net');
const port = 3000;
const host = '127.0.0.1';

const server = net.createServer();
server.listen(port, host, () => {
    console.log('TCP Server is running on port ' + port + '.');
});

let sockets = [];

server.on('connection', function (sock) {
    console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
    sockets.push(sock);

    sock.on('data', function (data) {
        console.log('DATA ' + sock.remoteAddress + ': ' + data);
    });
});

这是我的进一步 HTML:

<!doctype html>
<html lang="en">

<head>
    <title>Hello, world!</title>
</head>

<body>
    <div id="content"></div>
</body>

</html>

Java简单请求:

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class NodeJsEcho { 

    public static void main(String[] args) throws UnknownHostException, IOException {
        Socket s = null;
        s =  new Socket("127.0.0.1", 3000);
        OutputStream os = s.getOutputStream();
        PrintWriter ps = new PrintWriter(os, true);
        ps.write("TEST");
        ps.flush();
        s.close();
    }
}

您或许应该考虑使用 socket.io 来交流和更新您的 HTML。

为此,根据您的代码,这可能是一个示例(确保您对其进行编辑以适合您的目的):

NodeJS:

const net = require('net');
const port = 3000;
const host = '127.0.0.1';
const server = net.createServer();
const io = require("socket.io").listen(4000);
let socketio=undefined;
let sockets = [];

io.on('connection', socket=>{
    socketio=socket;
});

server.listen(port, host, () => {
    console.log('TCP Server is running on port ' + port + '.');
});


server.on('connection', sock => {
    console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
    sockets.push(sock);
    socketio.emit('updateHtml', {key: "value"});
    sock.on('data', function (data) {
        console.log('DATA ' + sock.remoteAddress + ': ' + data);
    });
});

HTML:

<!doctype html>
<html lang="en">

<head>
    <title>Hello, world!</title>
</head>

<body>
    <div id="content">changeMe</div>
    <script src="socket.io/socket.io.js" />
    <script>
        var socket = io('http://localhost:4000');

        socket.on('updateHtml', function (data) {
            document.getElementById("content").innerHTML = data.key;
        });

        socket.on('disconnect', function () { });
    </script>
</body>

</html>