问题
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>
回答1:
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.
来源:https://stackoverflow.com/questions/41627659/socketio-data-undefined