Files
tqxz-sn-message-platform/app/middleware/socket/socketServer.js
2026-06-01 17:47:16 +08:00

90 lines
3.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const net = require('net');
module.exports = (app) => {
const { middleware } = app;
const shunt = middleware.shunt;
net.createServer(function (socket) {
socket.on('lookup', function (data) {
console.log(data);
console.log('lookup')
});
socket.on('connection', function (data) {
console.log(data);
console.log('socket客户端已连接');
});
socket.on('data', async function (data) {
let response = "000000068100";
socket.write(Buffer.from(response, 'hex'));
let value = data.toString('hex');
if (value.length > 60) {
let Msg_id_len, length, Msg_id, msgID, snNumber, Total_len, Cmd_code, Token, Content_len, Content, msgData;
Msg_id_len = value.slice(50, 52);
length = 52 + parseInt(Msg_id_len, 16) * 2;
Msg_id = value.slice(52, length);
msgID = Buffer.from(Msg_id, 'hex').toString();
snNumber = msgID.split("_")[0].padStart(8, '0');
if (/^\d+$/.test(snNumber) && !/^0+$/.test(snNumber)) {
Total_len = value.slice(0, 8);
Cmd_code = value.slice(8, 10);
Token = value.slice(10, 50);
Content_len = value.slice(length, length + 4);
Content = value.slice(length + 4, value.length);
msgData = Buffer.from(Content, 'hex').toString('ascii');
// socket接收消息后触发事件监听器,将消息发送给websocket客户端并存储在数据库中
shunt.socketEmitter().emit(snNumber, { msg_data: msgData, created_at: new Date() });
const shortMsg = await app.curl('http://127.0.0.1:' + app.server.address().port + '/shortMsg', {
dataType: 'json',
contentType: 'application/x-www-form-urlencoded',
method: 'POST',
timeout: 3000,
data: {
sn_number: snNumber,
original_msg: value,
msg_data: msgData,
created_at: new Date()
},
});
if (shortMsg.data.code == 404) {
await app.curl('http://127.0.0.1:' + app.server.address().port + '/saveUnknown', {
dataType: 'json',
contentType: 'application/x-www-form-urlencoded',
method: 'POST',
timeout: 3000,
data: {
msg_id: msgID,
sn_number: snNumber,
original_msg: value,
msg_data: msgData,
created_at: new Date()
},
});
}
}
}
});
socket.on('end', function (data) {
console.log(data);
console.log('end');
});
socket.on('timeout', function (data) {
console.log(data);
console.log('空闲超时');
});
socket.on('drain', function (data) {
console.log(data);
console.log('写缓存为空');
});
socket.on('error', function (data) {
console.log(data);
console.log('发生错误');
});
socket.on('close', function (data) {
console.log(data);
console.log('socket客户端已断开连接');
});
socket.pipe(socket);
}).listen(8100, function () {
console.log('socket服务器已启动,监听端口:8100');
});
}