Files
BR_YKC/4G/code/core/linksocket.lua

84 lines
2.6 KiB
Lua
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.
require "socket"
require "log"
-- 目标服务器IP和端口
local ip, port = "74538dd1hu30.vicp.fun", "50752"
-- 连接数量
local clientCount = 1
-- 存储所有客户端
local clients = {}
-- 初始化多个socket连接
for i = 1, clientCount do
local client = {
id = i,
socket = nil,
connected = false
}
-- 为每个socket创建独立的连接任务
sys.taskInit(function()
while true do
while not socket.isReady() do sys.wait(1000) end
client.socket = socket.tcp()
log.debug("Client " .. client.id .. ": Connecting to " .. ip .. ":" .. port)
while not client.socket:connect(ip, port) do
log.warn("Client " .. client.id .. ": Connection failed, retrying...")
sys.wait(2000)
end
client.connected = true
log.debug("Client " .. client.id .. ": Connected successfully")
-- 发送连接成功信息到串口
uart.write(1, "Socket " .. client.id .. " connected\r\n")
-- 保持连接并处理数据
while client.socket:asyncSelect(60, "ping") do end
client.connected = false
client.socket:close()
log.error("Client " .. client.id .. ": Disconnected")
-- 发送断开连接信息到串口
end
end)
-- 存储客户端
clients[i] = client
end
local function toHexcode(str)
local hexcode = ""
for i = 1, #str do
hexcode = hexcode .. string.format("%02X", str:byte(i))
end
return hexcode
end
-- 测试代码,异步回调接收数据
sys.subscribe("SOCKET_RECV", function(id)
-- 遍历所有客户端,找到对应的连接
for i, client in ipairs(clients) do
if client.socket and client.socket.id == id then
-- 转发到串口添加socket标识并清理数据
local data = client.socket:asyncRecv()
log.info("Client " .. client.id .. ": Received data: " .. toHexcode(data))
-- 转发到串口添加socket标识
local frame = string.char(0x55) .. string.char(0xAA) .. string.char(0x01) .. string.char(i) .. string.char(#data) .. data .. string.char(0xAA) .. string.char(0x55)
uart.write(1, frame)
break
end
end
end)
-- 发送数据到指定socket
function sendToSocket(id_byte, msg)
if clients[id_byte] and clients[id_byte].socket and clients[id_byte].connected then
clients[id_byte].socket:asyncSend(msg)
else
log.error("Socket " .. id_byte .. " not connected or does not exist")
end
end