gpt4 book ai didi

javascript - 使用nodejs tcp服务器接收客户端数据

转载 作者:太空宇宙 更新时间:2023-11-04 00:50:47 26 4
gpt4 key购买 nike

我想从正在向我的服务器发送数据的客户端接收数据。这是我的代码,它将传入的数据插入 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

最佳答案

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);
});

关于javascript - 使用nodejs tcp服务器接收客户端数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32567122/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com