首页 > 解决方案 > 每次单击 HTML 和 javascript 上的按钮时,使用 TCP 向客户端发送一个值,其中每个按钮发送一个不同的值

问题描述

我已经投入到自己的项目中,这样我就可以了解网络和使用网络的应用程序。但是,我目前被困在一个点上,还没有找到正确的答案。我通过 TCP 连接到远程设备。它正在监听,我想在每次按 A、B 或 C 时发送一个不同的整数值。我可以发送一个值,但只能发送一次,而且我也不知道如何更改它(它只发送我已经发送的值为其设置,例如 32)。

例如,我想为 A 发送 131,为 B 发送 1118,为 C 发送 12819。数字只是随机的以举例说明主题。

<ul id="menu">
        <li class="parent"><a href="#">Encode Mode<span class="expand">&raquo;</span></a>
            <ul class="child">
            <li><a href="#" nowrap>A</a></li>
            <li><a href="#" nowrap>B</a></li>
            <li><a href="#" nowrap>C</a></li>
            </ul>
        </li>
</ul>
   var net = require('net');

    var setval = 32;

    var buf = new Buffer(1024);
    buf.writeInt32LE(setval, 0); //max value to send 2147483647

    let client = new net.Socket();
    client.connect(PORT, IP , () => {
    console.log("Connected");
    client.write(buf); //This will send the byte buffer over TCP
    });

标签: javascripthtmltcp

解决方案


在您的html 文件中,您可以使用三个不同的 id 创建三个不同的按钮

<button id="btn1"></button>
<button id="btn2"></button>
<button id="btn3"></button>

然后为您的按钮在您的js 文件中创建三个不同的 eventListener

document.getElementById("btn1").addEventListener('click', function() {
    const data = {value: 131};
    const options = {
        method: 'POST',
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(data)
    };
    await fetch('/startMyFunction', options); 
})

其他两个具有不同值的按钮相同

在您的服务器端 js 文件中,您必须创建一个这样的函数

myFunction(val) {

var buf = new Buffer(1024);
buf.writeInt32LE(val, 0); //max value to send 2147483647

// Assumes the connection is established
client.write(buf); //This will send the byte buffer over TCP
});
} 

例如,您还必须在路径上聆听

app.post('/startMyFunction', (req, res) => {
    // read the parameter out of the request body
    const val = req.body.value
    // Call the function with this parameter
    myFunction(val);
 });

代码片段(改编)来自我的存储库,您可以在此处查看完整代码 https://github.com/CreaTorAlexander/corona-motivator


推荐阅读