1
czw
2025-07-03 c066f9be49a723b39104e4a199b35604aa772b7f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#region    [自定义类-VS][20250612005504281][TcpServer]
#region    [自定义类-VS][20250605212036245][TcpServer]
using GZ.Device.PLC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using GZ.Modular.Redis;
 
namespace GZ.Projects.AuxAllWCS
{
 
    public class TcpServer
    {
        public static Dictionary<string, string> TrayIps = new Dictionary<string, string>();
        public TcpServer(string ip)
        {
            Init(ip);
        }
        private void Init(string ip)
        {
            //创建一个新的Socket,这里我们使用最常用的基于TCP的Stream Socket(流式套接字)
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                //将该socket绑定到主机上面的某个端口
                socket.Bind(new IPEndPoint(IPAddress.Parse(ip), 2025));
                //启动监听,并且设置一个最大的队列长度
                socket.Listen(30);
                //开始接受客户端连接请求
                socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        public static Dictionary<string, Socket> clients = new Dictionary<string, Socket>();
        public static Dictionary<string, byte[]> buffers = new Dictionary<string, byte[]>();
        public static void ClientAccepted(IAsyncResult ar)
        {
 
            var socket = ar.AsyncState as Socket;
            var client = socket.EndAccept(ar);
            string remote_ip = ((System.Net.IPEndPoint)client.RemoteEndPoint).Address.ToString();
            if (clients.Keys.Contains(remote_ip))
            {
                clients[remote_ip] = client;
            }
            else
            {
                clients.Add(remote_ip, client);
            }
            if (!buffers.Keys.Contains(remote_ip))
            {
                buffers.Add(remote_ip, new byte[1024]);
            }
            //给客户端发送一个欢迎消息
            //client.Send(Encoding.Unicode.GetBytes("Hi there, I accept you request at " + DateTime.Now.ToString()));
            Console.WriteLine(remote_ip);
 
            try
            {
                client.BeginReceive(buffers[remote_ip], 0, buffers[remote_ip].Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), client);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"【接收客户端的消息异常0】:" + ex.Message);
            }
            //准备接受下一个客户端请求
            socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);
        }
 
 
        public static void ReceiveMessage(IAsyncResult ar)
        {
            try
            {
                var socket = ar.AsyncState as Socket;
                string remote_ip = ((System.Net.IPEndPoint)socket.RemoteEndPoint).Address.ToString();
                var length = socket.EndReceive(ar);
                if (length == 0)
                {
                    clients.Remove(remote_ip);
                    buffers.Remove(remote_ip);
                    return;
                }
                else
                {
                    if (!clients.Keys.Contains(remote_ip))
                    {
                        clients.Add(remote_ip, socket);
                    }
                    if (!buffers.Keys.Contains(remote_ip))
                    {
                        buffers.Add(remote_ip, new byte[1024]);
                    }
                }
                try
                {
                    if (buffers.Keys.Contains(remote_ip))
                    {
                        //读取出来消息内容
                        var message = GetHexString(buffers[remote_ip], length);
                        //16   10
                        // Console.WriteLine($"{DateTime.Now.ToString("hh:mm:ss")} ---> " + remote_ip + "  :   " + message);
                        //if (message.Substring(0, 4) == "3f00" && message.Substring(message.Length - 4) == "0d0a")
                        //{
                        //    //显示消息
                        //    //string msg = message.Replace(@"0d", "").Replace(@"0a", "").Replace(@"0d0a", "").Trim();
                        //    //PlcHelper.Receive(remote_ip, msg);
                        //    //Array.Clear(buffers[remote_ip], 0, buffers[remote_ip].Length);//清空当前IP Buffer
                        //}
                        //else
                        //{
                        Console.WriteLine($"【TCP信息协议 {DateTime.Now.Millisecond}】:IP:{remote_ip},MSG:{message}");
                        var mg = Encoding.ASCII.GetString(PlcHelper.Hex2Bin(message));
                        if (mg.Length > 10)
                        {
                            mg = mg.Substring(0, 10);
                        }
                        Console.WriteLine(mg);
                        if (mg.StartsWith("DK"))//&& mg.Trim().Length == "DK01000024".Length
                        {
                            LogHelper.Info($"扫码器 >{remote_ip} -{mg}");
                            if (TrayIps.TryGetValue(remote_ip, out string traycode))
                            {
                                TrayIps[remote_ip] = mg;
                            }
                            else TrayIps.Add(remote_ip, mg);
 
                            RedisHelper.Add("Scan" + (remote_ip.Split('.').LastOrDefault()), mg, out string msg);
                            RedisHelper.Add("Scan" + (remote_ip.Split('.').LastOrDefault()) + "#time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), out msg);
                            //Console.WriteLine("TOFF");
                            //var mst = PlcHelper.Hex2Bin("544F4646");
                            //TcpServer.TcpServerSend(remote_ip, mst);
                        }
                        //}
                    }
                    else
                    {
                        if (!buffers.Keys.Contains(remote_ip))
                        {
                            buffers.Add(remote_ip, new byte[1024]);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"【处理客户端的消息异常2】:" + ex.StackTrace);
                    throw;
                }
                //接收下一个消息(因为这是一个递归的调用,所以这样就可以一直接收消息了)
                socket.BeginReceive(buffers[remote_ip], 0, buffers[remote_ip].Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
 
        private static string GetHexString(byte[] buffer, int lenght)
        {
            return BitConverter.ToString(buffer, 0, lenght).Replace("-", string.Empty).ToLower();
        }
 
        public static bool TcpServerSend(string ip, byte[] msg)
        {
            LogHelper.Info($"TcpServerSend >{ip}:{msg}");
            if (clients.Keys.Contains(ip))
            {
                var client = clients[ip];
                if (client.Connected)
                {
                    try
                    {
                        client.Send(msg);
                        LogHelper.Info($"TcpServerSend > 发送成功。");
                        return true;
                    }
                    catch (SocketException ex)
                    {
                        Console.WriteLine(ex.Message);
                        clients[ip].Close();
                        clients.Remove(ip);
                    }
                }
                else
                {
                    clients[ip].Close();
                    clients.Remove(ip);
                }
            }
            else
            {
                Console.WriteLine("未找到设备的链接:" + ip);
            }
            return false;
 
        }
 
        public static int GetBitdata(int num, int wid)
        {
            string bstr = Convert.ToString(num, 2);
            if (bstr.Length <= wid)
            {
                return 0;
            }
            return bstr[bstr.Length - wid - 1] - '0';
        }
        public static int SetBinaryDigit(int number, int n, int value)
        {
            if (value != 0 && value != 1)
                throw new ArgumentException("Value must be 0 or 1.");
 
            string binaryStr = Convert.ToString(number, 2);
 
            // 如果 n 超出当前位数,补 0 扩展
            while (binaryStr.Length <= n)
            {
                binaryStr = "0" + binaryStr;
            }
 
            // 修改第 n 位(从右往左,最低位是第 0 位)
            char[] binaryChars = binaryStr.ToCharArray();
            binaryChars[binaryChars.Length - 1 - n] = value == 1 ? '1' : '0';
 
            // 转换回十进制
            return Convert.ToInt32(new string(binaryChars), 2);
        }
        public static List<string> GetStaticClients() => clients.Keys.ToList();
        public static Dictionary<string, string> GetStaticScan() => TrayIps;
    }
}
 
#endregion [自定义类-VS][20250605212036245][TcpServer]
#endregion [自定义类-VS][20250612005504281][TcpServer]