我想从正在向我的服务器发送数据的客户端接收数据。这是我将传入数据插入msql的代码
var net = require('net');
var mysql = require('mysql');
var randomstring = require("randomstring");
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
socket.on('data', function (data) {
var connection = mysql.createConnection({
host : 'seizedserver.com',
user : 'federal',
password : '123456',
database : 'hanging_tree'
});
connection.connect();
/*
connection.query('SELECT data from gps', function(err, rows) {
if (err) throw err;
console.log('The solution is: ', rows[0]);
});
*/
var post = {data: data};
var query = connection.query('INSERT INTO gps SET ?', post, function(err, result) {
});
console.log(query.sql);
connection.end();
});
server.listen(1337, '127.0.0.1');
计划是将传入的数据插入到我创建的mysql表中,但我不确定我是否正确使用了数据事件。
我正确使用数据事件吗?。
当我永远运行我的脚本
时,我收到此错误/var/www/html/server.js:9
socket.on('data', function (data) {
^
ReferenceError: socket is not defined
at Object.<anonymous> (/var/www/html/server.js:9:2)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
error: Forever detected script exited with code: 8
答案 0 :(得分:1)
socket
仅在服务器的回调中定义:
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
// socket is undefined here
socket.on('data', function (data) {
var connection = mysql.createConnection({
host : 'seizedserver.com',
user : 'federal',
password : '123456',
database : 'hanging_tree'
});
应该是:
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
// socket is defined here and in scope
socket.on('data', function (data) {
var connection = mysql.createConnection({
host : 'seizedserver.com',
user : 'federal',
password : '123456',
database : 'hanging_tree'
});
socket.pipe(socket);
});