Initial commit
This commit is contained in:
58
tcp-command-frame/client.mjs
Normal file
58
tcp-command-frame/client.mjs
Normal file
@@ -0,0 +1,58 @@
|
||||
// client.mjs
|
||||
import net from 'node:net';
|
||||
|
||||
const HOST = '192.168.2.25'; // <-- set Pico IP
|
||||
const PORT = 5505;
|
||||
|
||||
function buildFrame(cmd, payload) {
|
||||
const len = payload.length;
|
||||
const frame = Buffer.alloc(3 + len);
|
||||
|
||||
frame[0] = cmd;
|
||||
frame[1] = len & 0xff; // len_lo
|
||||
frame[2] = (len >> 8) & 0xff; // len_hi
|
||||
payload.copy(frame, 3);
|
||||
|
||||
return frame;
|
||||
}
|
||||
|
||||
function parseFrame(buffer) {
|
||||
if (buffer.length < 3) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cmd = buffer[0];
|
||||
const len = buffer[1] | (buffer[2] << 8);
|
||||
|
||||
if (buffer.length < 3 + len) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const payload = buffer.subarray(3, 3 + len);
|
||||
return { cmd, payload };
|
||||
}
|
||||
|
||||
const socket = net.createConnection({ host: HOST, port: PORT });
|
||||
|
||||
let rxBuffer = Buffer.alloc(0);
|
||||
|
||||
socket.on('connect', () => {
|
||||
const payload = Buffer.from('Test');
|
||||
const frame = buildFrame(0x10, payload);
|
||||
socket.write(frame);
|
||||
});
|
||||
|
||||
socket.on('data', (chunk) => {
|
||||
rxBuffer = Buffer.concat([rxBuffer, chunk]);
|
||||
|
||||
const frame = parseFrame(rxBuffer);
|
||||
if (frame) {
|
||||
console.log('CMD:', frame.cmd);
|
||||
console.log('Payload:', frame.payload.toString());
|
||||
socket.end();
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('error', (err) => {
|
||||
console.error(err);
|
||||
});
|
||||
Reference in New Issue
Block a user