HTML应用程序通过TCP/IP客户端发送短字符串的最佳方式



我正在做一个项目,为了通知服务器,我必须通过TCP/IP套接字发送不同的字符串(START、PAUSE、STOP)。

我想做的是通过按下HTML应用程序上的按钮来发送字符串(START、STOP、PAUSE)。***在按下JSON文件上的按钮后,我将fs.writeFile作为一个空字符串。我只想在我的JSON文件中有一个字符串。

我尝试直接从客户端发送一些自定义字符串(clientSend.write('TEST');)并且服务器可以很好地接收

我尝试通过php和JSON文件发送不同的变量,但我似乎无法访问JSON文件,即使我的服务器正在运行。我想知道从html页面向客户端发送字符串的最佳方式是什么

我试图发送到php文件,然后再发送回JSON文件,但始终无法正常工作。

节点JS客户端:

const IP = '127.0.0.1';
const SENDPORT = 3456;
setInterval(function() { 
var clientSend = new net.Socket();
clientSend.connect(SENDPORT, IP, function() {
console.log('Connected');
fs.readFile('/string.json', (err, data) => { //might be wrong
if (err) throw err;
console.log(data);
});
clientSend.write(data);
clientSend.destroy();
});
clientSend.on('close', function() {
console.log('Connection closed');
clientSend.destroy();
});
}, 10000); 

HTML页面:

(...)
Start button:<button id="buttonStart"; style="background:green; 
cursor:pointer;width:300px;height:100px;">Start</button>
<br><br><br>>
Pause button:<button id="buttonStart"; style="background:orange; 
cursor:pointer;width:300px;height:100px;">Pause</button>
<br><br><br>>

Stop button:<button id="buttonStart"; style="background:red; 
cursor:pointer;width:300px;height:100px;">Stop</button>
<script 
src=https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js> 
</script>
<script>
var start = 'start';
//This is where I have no clue what to do
$('#buttonStart').click(function() {
$.post("json.php", {JSON.stringify(start)}
);}
</script>

PHP

<?php
$json = $_POST['start'];
/* sanity check */
if (json_decode($start) != null) {
$file = fopen('/string.json','w+');
fwrite($file, $start);
fclose($file);
}
else {
//
}
?>

现在我真正想要得到的是JSON文件中的数据。它也可能是一个.txt文件,或者之后我可以使用fs.read文件的任何其他文件。

我不能在HTML页面上使用任何NodeJS函数。

性能也很重要。如果有更好的选择张贴和阅读小字符串,请告诉我。

谢谢。

我编写的解决方案很好,但并不完整。我只是没有在php服务器上运行php代码,所以html页面读取的是一个简单的文本。

我下载了Wampserver,让php在这台服务器上运行,而不是一起运行所有东西,它运行得很好。

最新更新