I have a simple http server running in Node as a systemd service that receives data via a tcp socket (not a WS socket). Here's the code:
const net = require('net');
const HOST = '0.0.0.0';
const PORT = 6968;
const server = net.createServer();
server.listen(PORT, HOST);
console.log('Server listening on', PORT);
server.on('connection', function(sock) {
console.log('CONNECTED:');
sock.on('data', function (data) {
let message = data.toString().trim();
console.log('message is', message);
console.log('data is', data);
console.log('message type is', typeof(message));
console.log('data is', typeof(data));
});
});
An example of the type of data sent to this server is the following string:
Grateful Dead^LSugaree^L005:37^L0251-001^LM\r\n
The specific problem I'm having is that "let message = data.toString().trim()" is not returning the string that was sent to me. Instead, I'll get something that looks like this:
"[67B blob data]"
The console.log for the object ("data") received by the server shows something like this:
"<Buffer 44 72 61 67 67 69 6e 20 [etc.]>"
The typeof(message) is "string". The typeof(data) is "object".
I have been researching this all day and have tried many different things but nothing I've tried will return to me the string I'm looking for, though I can see the string by just looking at the port by entering the terminal command:
"socat TCP4-listen:6968,reuseaddr,fork -"
Does anyone see what I'm doing wrong?
CodePudding user response:
Here is an example stolen from this website: https://riptutorial.com/node-js/example/22405/a-simple-tcp-server
const net = require("net");
const HOST = "0.0.0.0";
const PORT = 6968;
const server = net.createServer();
server.listen(PORT, HOST);
console.log("Server listening on", PORT);
server.on("connection", function (socket) {
console.log("A new connection has been established.");
// Now that a TCP connection has been established, the server can send data to
// the client by writing to its socket.
socket.write("Hello, client.");
// The server can also receive data from the client by reading from its socket.
socket.on("data", function (chunk) {
console.log(`Data received from client: ${chunk.toString().trim()}.`);
});
// When the client requests to end the TCP connection with the server, the server
// ends the connection.
socket.on("end", function () {
console.log("Closing connection with the client");
});
// Don't forget to catch error, for your own sake.
socket.on("error", function (err) {
console.log(`Error: ${err}`);
});
});
CodePudding user response:
In case any future person stumbles on this, the problem was (is) I'm an idiot. The simple solution was to use "message" to create an array:
let dataArray = message.split('\f');
(I happened to know that the data being sent to me used "\f" as a delimiter.)
Then I could use the array to process the data as I wished.