我现在就开始用webSockets进行冒险,如果你能帮我的话,我会很乐意的。
我有一个基本的问题,但我不能自己解决:(
我有一个来自Node.js和MySQL查询的WebSocket(ws)服务器,我可以在控制台上看到查询结果,但在客户端看不到。
服务器.JS
const WebSocket = require('ws');
var mysql = require('mysql');
const wss = new WebSocket.Server({ port: 3000 });
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: 'db'
});
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("SELECT * FROM hardware;", function (err, result) {
if (err) throw err;
ws.send(result); //???????????????
console.log("Result: " + JSON.stringify(result));
});
});
ws.send('something');
//ws.send(JSON.stringify({topic:'test', data:'tst2'}));
});
以及客户端index.html
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<button type="button" onclick="getSql()">GET</button>
</div>
<script>
function getSql() {
var sock = new WebSocket("ws://localhost:3000");
sock.onopen = function(event) {
alert("socket ok");
setTimeout(function() {
sock.send("hey");
}, 1000);
};
sock.onmessage = function(event) {
console.log(event);
if (event.data) {
console.log(event.data);
}
}
}
</script>
</body>
</html>
我想实现的是从SQL查询中获得结果,但总是得到空值。
你能帮我解决我的基本问题吗?
示例来自:
https://www.w3schools.com/nodejs/nodejs_mysql_select.asp
https://www.npmjs.com/package/ws
谢谢你的问候。