Windows C#中未将TCP消息写入文件

如何解决Windows C#中未将TCP消息写入文件

我有这些字节:

1 68 78 77 51 51 49 32 49 50 49 51 48 55 13 10 71 71 32 69 89 86 73 89 68 89 88 13 10 49 50 49 51 48 55 32 69 89 86 73 90 80 90 66 13 10 2 71 79 79 68 32 68 65 89 44 13 10 68 73 83 82 69 71 65 82 68 32 84 72 73 83 32 65 82 82 32 77 83 71 32 66 69 76 79 87 13 10 40 65 82 82 45 76 89 84 73 84 47 65 55 48 49 51 45 69 89 86 73 45 69 89 86 73 49 50 52 54 41 13 10 86 78 79 32 66 82 73 69 70 73 78 71 13 10 11 3 84 32 49 50 48 53 13 10 45 83 83 82 67 79 68 69 32 65 55 55 49 51 13 10 45 83 69 81 85 69 78 67 69 68 65 84 65 13 10 45 84 88 84 73 77 69 32 50 48 48 56 49 50 49 51 48 52 49 56 13 10 45 78 85 77 32 52 54 13 10 11 3

另一个例子:

1 68 78 77 51 51 54 32 49 50 49 51 49 55 13 10 70 70 32 69 89 75 65 89 68 89 88 32 69 89 86 73 89 68 89 88 13 10 49 50 49 51 49 55 32 69 85 67 72 90 77 70 80 13 10 2 40 68 69 80 45 76 89 70 84 71 45 69 89 75 83 49 51 48 56 45 69 89 75 83 45 68 79 70 47 50 48 48 56 49 50 41 13 10 11 3 49 83 50 32 68 79 70 47 50 48 48 56 49 50 13 10 32 82 69 71 47 89 76 67 83 68 32 69 69 84 47 69 80 87 87 48 48 49 53 32 67 79 68 69 47 53 48 50 67 67 68 32 82 86 82 47 50 48 48 32 79 80 82 47 66 84 73 32 79 82 71 78 47 69 86 82 65 66 84 73 79 13 10 32 80 69 82 47 67 32 82 77 75 47 80 72 79 78 69 32 67 84 67 58 32 48 48 51 55 49 54 55 55 56 56 52 50 54 41 13 10 11 3 51 54 32 69 71 78 77 13 10 45 80 66 78 47 65 49 66 49 67 49 68 49 76 49 79 49 79 50 83 50 32 68 79 70 47 50 48 48 56 49 50 32 82 69 71 47 72 65 76 83 66 32 69 69 84 47 69 86 82 82 48 48 51 57 32 69 89 86 76 48 48 51 57 13 10 69 83 65 65 48 48 52 50 32 69 75 68 75 48 49 49 48 32 69 68 86 86 48 49 50 52 32 69 72 65 65 48 49 52 51 32 69 71 84 84 48 50 48 49 32 67 79 68 69 47 52 55 49 69 69 49 32 82 86 82 47 48 55 53 13 10 79 80 82 47 87 90 90 32 79 82 71 78 47 69 68 68 70 87 90 90 88 32 80 69 82 47 67 32 82 77 75 47 84 67 65 83 41 13 10 11 3

数据读取(ascii控制字符在此处不可见,因此我在下面添加图片,应将符合要求的部分写入文件):

DNM336 121317
FF EYKAYDYX EYVIYDYX
121317 EUCHZMFP
(DEP-LYFTG-EYKS1308-EYKS-DOF/200812)
1S2 DOF/200812
 REG/YLCSD EET/EPWW0015 CODE/502CCD RVR/200 OPR/BTI ORGN/EVRABTIO
 PER/C RMK/PHONE CTC: 0037167788426)
36 EGNM
-PBN/A1B1C1D1L1O1O2S2 DOF/200812 REG/HALSB EET/EVRR0039 EYVL0039
ESAA0042 EKDK0110 EDVV0124 EHAA0143 EGTT0201 CODE/471EE1 RVR/075
OPR/WZZ ORGN/EDDFWZZX PER/C RMK/TCAS)

enter image description here

和一个程序,侦听这些传入的字节,并在它们匹配条件时将它们写入文件: 邮件以SOH(1字节)开头,以EYX(3字节)结尾,正文中包含STX(2字节)

当我在Mac上进行测试时,它似乎对我来说很好用,但是我们在Windows上的服务器上进行了部署,有时似乎没有消息写... 同一字节数组中可能会出现几条消息。这是我的程序的样子:

class Program
    {
        private const string V_AFTN = "";
        private const string K_AFTN = "";
        private const string P_AFTN = "";

       static void Main(string[] args)
        {
            string folderProduction = @"";
            string folderTesting = @"";

            var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json")
                .AddEnvironmentVariables()
                .Build();

            Parallel.Invoke(() => Run(folderProduction,80,"Production"),() => Run(folderTesting,configuration.GetValue<int>("PortSettingsTesting:Port"),"Testing"));
        }


        private static void Run(string folderName,int port,string env)
        {
            connection:
            try
            {
                string[] switchStrings = {V_AFTN,K_AFTN,P_AFTN};
                string pathString = "";
                string airportFolder = "";
                string fileName = "";
                TcpListener server = new TcpListener(IPAddress.Any,port);
                
                // Start listening for client requests.
                server.Start();
                Console.WriteLine(env + " TCP listener started on port: " + port);

                // Enter the listening loop.
                while (true)
                {
                    try
                    {
                        Console.WriteLine(env + " Waiting for connection");
                        // Perform a blocking call to accept requests.
                        TcpClient client = server.AcceptTcpClient();
                        Console.WriteLine(env +  " Connected!");
                        Console.WriteLine("---------------------------------------------");
                        string result = null;
                        // Get a stream object for reading and writing
                        NetworkStream stream = client.GetStream();

                        Console.WriteLine("Buffer size: " + client.ReceiveBufferSize);
                        // Buffer for reading data
                        byte[] bytes = new byte[client.ReceiveBufferSize];
                        while (stream.Read(bytes,bytes.Length) != 0)
                        {
                            var bytesArray = bytes.TakeWhile(x => x != 0).ToArray();
                            for (int i = 0; i < bytesArray.Length; i++)
                            {
                                Console.Write(bytesArray[i] + " ");
                            }
                            var data = Encoding.ASCII.GetString(bytesArray);
                            Console.WriteLine("\r\n DATA READ: \r\n" + data);
                            Console.WriteLine();
                            for (int j = 0; j < bytesArray.Length; j++)
                            {
                                string byteToString = "";

                                if (result == null && (bytesArray[j] == 0 || String.IsNullOrWhiteSpace(Encoding.ASCII.GetString(new[] {bytesArray[j]}))))
                                    continue;
                                
                                if (bytesArray[j] == 1)
                                {
                                    byteToString = "\x01";
                                }
                                else if (bytesArray[j] == 3 && result != null)
                                {
                                    byteToString = "\x03";
                                }
                                else if (bytesArray[j] == 2 && result != null)
                                {
                                    byteToString = "\x02";
                                }
                                else if (result != null)
                                {
                                    byteToString = Encoding.ASCII.GetString(new[] {bytesArray[j]});
                                }
                                
                                result += byteToString;

                                if (result.StartsWith("\x01") && result.Contains("\x02") && result.Contains("\x03"))
                                {
                                    switch (switchStrings.FirstOrDefault<string>(s => result.Contains(s)))
                                    {
                                        case V_AFTN:
                                            fileName = V_AFTN;
                                            break;
                   
                                        default:
                                            fileName = "Unknown";
                                            break;
                                    }
                                    
                                    pathString = Path.Combine(folderName,airportFolder);

                                    if (!Directory.Exists(pathString))
                                    {
                                        Directory.CreateDirectory(pathString);
                                    }
                            
                                    var id = GenerateIncrementalId(folderName,fileName);
                                    CreateTextFile(pathString,fileName + "_" + DateTime.Now.ToString("yyMMdd_hhmm") + $"_{id}" + ".txt",result);
                                    
                                    Console.WriteLine(env + " File created");
                                    result = null;
                                }
                            }
                        }

                        Console.WriteLine(env + " Finished");
                        // Shutdown and end connection
                        client.Close();
                    }

                    catch (SocketException e)
                    {
                        Console.WriteLine(env + " SocketException: {0}",e);
                    }
                    finally
                    {
                        // Stop listening for new clients.
                        server.Stop();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(env + " Failed to connect: " + e.Message);
                goto connection;
            }
        }

        private static int GenerateIncrementalId(string path,string airport)
        {
            DirectoryInfo d = new DirectoryInfo(path);
            var files = d.GetFiles("*.txt").Where(x => x.Name.Contains(airport));
            var fileInfos = files as FileInfo[] ?? files.ToArray();
            if (!fileInfos.Any())
            {
                // if there's no file yet,return 1
                return 1;
            }
            // return next incremental ID
            return fileInfos.Count() + 1;
        }

        private static void CreateTextFile(string path,string textTitle,string data)
        {
            var pathToWrite = Path.Combine(path,textTitle);
            if (!File.Exists(pathToWrite))
            {
                var charsToRemove = new [] {' ','\n','\r'};
                data = data.TrimEnd(charsToRemove);
                File.Create(pathToWrite).Close();
                using var sw = new StreamWriter(pathToWrite);
                Console.WriteLine("WRITING DATA: \r\n" + data);
                sw.WriteLine(data);
                Console.WriteLine("Writing data to: " + pathToWrite);
                data = null;
                sw.Flush();
            }
        }
    }

我知道操作系统应该不是问题,但我对此一无所知,不知道这里可能有什么问题

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res