简体   繁体   中英

socketIO data undefined

I'm trying to send data from my client to my server side. I only get undefined . I would like the user to click the ledOn function to send 1 and also click the ledOff to send 0 to the server.

server.js

io.sockets.on('connection', function(socket){

    socket.on('ON', function (data) {
        console.log(data);

    });
    socket.on('OFF', function (data) {
        console.log(data);

    });
});

client.js

function ledOn() {
 socket.emit ('ON');
     document.getElementById("ON").value = "1"
 console.log("Led is ON ");
 }

 function ledOff() {
 socket.emit('OFF');
     document.getElementById("OFF").value = "0"
 console.log("Led is Off");

 }

index.HTML

<div id="ON">
<input type="submit" value="Led ON" onclick="ledOn()">
</div>
<div id="OFF">
<input type="submit" value="Led OFF" onclick="ledOff()">
</div>

Change client.js to emit some data in the case of an "ON" or "OFF" event. For example, below, I am sending a "1" and "0" in ledOn() and ledOff() respectively.

function ledOn() {
    socket.emit ('ON', "1");
    document.getElementById("ON").value = "1"
    console.log("LED is on");
 }

 function ledOff() {
    socket.emit('OFF', "0");
    document.getElementById("OFF").value = "0"
    console.log("LED is off");
 }

Check out the Socket.IO docs to see some of their examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM