using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using Newtonsoft.Json; namespace TcpServerApp { class Program { static void Main(string[] args) { // 监听端口 int port = 43917; IPAddress ipAddress = IPAddress.Any; // 创建 TCPListener TcpListener server = new TcpListener(ipAddress, port); server.Start(); Console.WriteLine($"TCP Server started on {ipAddress}:{port}"); while (true) { // 等待客户端连接 TcpClient client = server.AcceptTcpClient(); Console.WriteLine("Client connected"); // 获取客户端流 NetworkStream stream = client.GetStream(); byte[] buffer = new byte[1024]; // 持续监听客户端数据 while (true) { int bytesRead = 0; try { bytesRead = stream.Read(buffer, 0, buffer.Length); } catch (Exception ex) { Console.WriteLine($"Error reading from stream: {ex.Message}"); break; } if (bytesRead == 0) break; // 客户端断开连接 // 将接收到的字节转换为字符串 string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesRead); Console.WriteLine($"Received: {receivedData}"); // 检查是否接收到目标字符串 if (receivedData.Contains("CallDeviceDZ")) { // 配置文件路径 string configFilePath = "config.json"; var messages = LoadMessagesFromConfig(configFilePath); Console.WriteLine("Specific message received, starting to send the entire JSON array..."); SendMessages(stream, messages); } else if (receivedData.Contains("GetFaultRptByTime")) { // 配置文件路径 string configFilePath = "1.txt"; var messages = LoadMessagesFromConfig(configFilePath); Console.WriteLine("Specific message received, starting to send the entire JSON array..."); SendMessages(stream, messages); } } } } // 从配置文件加载消息数组 static dynamic LoadMessagesFromConfig(string configFilePath) { try { string jsonContent = File.ReadAllText(configFilePath, Encoding.UTF8); //dynamic config = JsonConvert.DeserializeObject(jsonContent); return jsonContent; // 返回动态对象数组 } catch (Exception ex) { Console.WriteLine($"Error reading config file: {ex.Message}"); return default;// { new { error = "Failed to load messages" } }; // 返回错误消息 } } // 一次性发送整个消息数组 static void SendMessages(NetworkStream stream, dynamic messages) { // 将整个消息数组转换为 JSON 字符串 //string jsonMessage = JsonConvert.SerializeObject(messages); // 将 JSON 字符串转换为字节数组 byte[] buffer = Encoding.UTF8.GetBytes("OK"+messages); // 发送消息 stream.Write(buffer, 0, buffer.Length); Console.WriteLine("Entire JSON array sent to client."); } } }