wzp
2021-07-28 864986e4cad03f6b9bba9a7e65379db496b62a6a
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
namespace AsiaINFO.SMS.CMPP2
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Net.Sockets;
    using System.Runtime.CompilerServices;
    using System.Threading;
 
    public class CMPPClient
    {
        private bool _IsConnected;
        private NetworkStream _NetworkStream;
        private Thread _ReadResponseThread;
        private Queue<byte[]> _receiveQueue;
        private string _Source_Addr;
        private SyncEvents _syncEvents;
        private object _syncIsConnectedObject = new object();
        private static object _SyncLockObject = new object();
        private TcpClient tc;
 
        public event MsgEventDelegate ErrorEvent;
 
        public event MsgEventDelegate MsgEvent;
 
        public event ThreadStateDelegate ThreadStateEvent;
 
        public CMPPClient(Queue<byte[]> queue, SyncEvents cmppSyncEvents)
        {
            if ((queue == null) || (cmppSyncEvents == null))
            {
                throw new Exception("参数不能为空!");
            }
            this._receiveQueue = queue;
            this._syncEvents = cmppSyncEvents;
        }
 
        public void ActiveResp(uint SequenceId)
        {
            this.WriteToStreamWithLock(new CMPP_ACTIVE_TEST_RESP(SequenceId).ToBytes(), this._NetworkStream);
        }
 
        public void ActiveTest(uint SequenceId)
        {
            this.WriteToStreamWithLock(new MessageHeader(12, CMPP_Command_Id.CMPP_ACTIVE_TEST, SequenceId).ToBytes(), this._NetworkStream);
        }
 
        public void Connect(string Host, int Port, string UserID, string Password, uint SequenceId)
        {
            this._Source_Addr = UserID;
            CMPP_CONNECT cmpp_connect = new CMPP_CONNECT(this._Source_Addr, Password, DateTime.Now, 0x20, SequenceId);
            this.tc = new TcpClient();
            this.tc.Connect(Host, Port);
            if (this._NetworkStream != null)
            {
                try
                {
                    this._NetworkStream.Close();
                    this._NetworkStream = null;
                }
                catch (Exception)
                {
                }
            }
            this._NetworkStream = this.tc.GetStream();
            this.WriteToStreamWithLock(cmpp_connect.ToBytes(), this._NetworkStream);
            this.StartRun();
        }
 
        public void DeliverResp(ulong Msg_Id, uint Result, uint SequenceId)
        {
            this.WriteToStreamWithLock(new CMPP_DELIVER_RESP(Msg_Id, Result, SequenceId).ToBytes(), this._NetworkStream);
        }
 
        public void Exit()
        {
            try
            {
                this.StopReceive();
                this._NetworkStream.Close();
                this._NetworkStream = null;
            }
            catch (Exception)
            {
            }
        }
 
        public bool IsStop()
        {
            if (((this._ReadResponseThread != null) && (this._ReadResponseThread.ThreadState != ThreadState.Stopped)) && ((this._ReadResponseThread.ThreadState != ThreadState.Aborted) && (this._ReadResponseThread.ThreadState != ThreadState.AbortRequested)))
            {
                return false;
            }
            return true;
        }
 
        private void OnError(string err)
        {
            if (this.ErrorEvent != null)
            {
                this.ErrorEvent(err);
            }
        }
 
        private void OnMsg(string msg)
        {
            if (this.MsgEvent != null)
            {
                this.MsgEvent(msg);
            }
        }
 
        protected void OnThreadState(ThreadState state)
        {
            if (this.ThreadStateEvent != null)
            {
                this.ThreadStateEvent(this, state);
            }
        }
 
        public void Query(DateTime Time, uint QueryType, string QueryCode, string Reserve, uint SequenceId)
        {
            this.WriteToStreamWithLock(new CMPP_QUERY(Time, QueryType, QueryCode, Reserve, SequenceId).ToBytes(), this._NetworkStream);
        }
 
        private byte[] ReadFromStreamWithLock(int Length, NetworkStream Stream)
        {
            try
            {
                lock (_SyncLockObject)
                {
                    return Util.ReadFromStream(Length, Stream);
                }
            }
            catch (Exception exception)
            {
                this.IsConnected = false;
                this.OnError(exception.Message);
            }
            return null;
        }
 
        private void Run()
        {
            try
            {
                while (!this._syncEvents.ExitThreadEvent.WaitOne(2, false))
                {
                    if (this._NetworkStream.CanRead && this._NetworkStream.DataAvailable)
                    {
                        this.OnMsg("接收到数据流...");
                        byte[] bytes = new byte[12];
                        bytes = this.ReadFromStreamWithLock(12, this._NetworkStream);
                        MessageHeader header = new MessageHeader(bytes);
                        byte[] dst = new byte[header.Total_Length];
                        Buffer.BlockCopy(bytes, 0, dst, 0, bytes.Length);
                        int length = ((int) header.Total_Length) - 12;
                        if (length > 0)
                        {
                            bytes = this.ReadFromStreamWithLock(length, this._NetworkStream);
                            Buffer.BlockCopy(bytes, 0, dst, 12, bytes.Length);
                        }
                        lock (((ICollection) this._receiveQueue).SyncRoot)
                        {
                            this._receiveQueue.Enqueue(dst);
                        }
                        this._syncEvents.NewItemEvent.Set();
                    }
                }
            }
            catch (Exception exception)
            {
                this.IsConnected = false;
                this.OnError("CMPPClient接收错误:" + exception.Message);
            }
            this.OnThreadState(ThreadState.Stopped);
        }
 
        public void StartRun()
        {
            try
            {
                if (this._ReadResponseThread == null)
                {
                    this._ReadResponseThread = new Thread(new ThreadStart(this.Run));
                }
                if (this._ReadResponseThread.ThreadState == ThreadState.Unstarted)
                {
                    this.OnThreadState(ThreadState.Running);
                    this._ReadResponseThread.Start();
                }
                else if (this._ReadResponseThread.ThreadState == ThreadState.Suspended)
                {
                    this.OnThreadState(ThreadState.Running);
                    this._ReadResponseThread.Resume();
                }
                else if (this._ReadResponseThread.ThreadState == ThreadState.Stopped)
                {
                    this.OnThreadState(ThreadState.Running);
                    this._ReadResponseThread = null;
                    this._ReadResponseThread = new Thread(new ThreadStart(this.Run));
                    this._ReadResponseThread.Start();
                }
            }
            catch (Exception exception)
            {
                this.OnError("CMPPClient启动错误:" + exception.Message);
            }
        }
 
        public void StopImmediately()
        {
            try
            {
                if (this._ReadResponseThread != null)
                {
                    this._ReadResponseThread.Abort();
                }
            }
            catch (ThreadAbortException)
            {
            }
            catch (Exception)
            {
            }
            finally
            {
                this.OnThreadState(ThreadState.Stopped);
            }
        }
 
        public void StopReceive()
        {
            this._syncEvents.ExitThreadEvent.Set();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="MsgId"></param>
        /// <param name="mobile"></param>
        /// <param name="MsgContent"></param>
        /// <param name="SequenceId"></param>
        /// <param name="Service_Id">企业帐户如 hs0055</param>
        /// <param name="FeeType"></param>
        /// <param name="FeeCode"></param>
        /// <param name="Src_Id">接入号:如 1069022600055</param>
        /// <param name="WapURL"></param>
        /// <param name="MsgSum"></param>
        /// <param name="MsgSub"></param>
        public void Submit(ulong MsgId, string mobile, string MsgContent, uint SequenceId, string Service_Id, string FeeType, string FeeCode, string Src_Id, string WapURL, uint MsgSum, uint MsgSub)
        {
            if ((mobile != null) && (mobile.Length == 11))
            {
                mobile = "86" + mobile;
            }
            this.Submit(MsgId, mobile, new string[] { mobile }, MsgContent, SequenceId, Service_Id, FeeType, FeeCode, Src_Id, WapURL, MsgSum, MsgSub);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="MsgId"></param>
        /// <param name="FeeTerminalId">收费</param>
        /// <param name="DestTerminalId"></param>
        /// <param name="MsgContent"></param>
        /// <param name="SequenceId"></param>
        /// <param name="Service_Id">企业帐户如 hs0055</param>
        /// <param name="FeeType">默认都为01</param>
        /// <param name="FeeCode">0</param>
        /// <param name="Src_Id">接入号:如 1069022600055</param>
        /// <param name="WapURL"></param>
        /// <param name="MsgSum"></param>
        /// <param name="MsgSub"></param>
        public void Submit(ulong MsgId, string FeeTerminalId, string[] DestTerminalId, string MsgContent, uint SequenceId, string Service_Id, string FeeType, string FeeCode, string Src_Id, string WapURL, uint MsgSum, uint MsgSub)
        {
            this.Submit(MsgId, 1, 0, FeeTerminalId, DestTerminalId, MsgContent, SequenceId, Service_Id, FeeType, FeeCode, Src_Id, WapURL, MsgSum, MsgSub);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="MsgId"></param>
        /// <param name="RegisteredDelivery">1表示需要上报状态报告</param>
        /// <param name="Fee_UserType"></param>
        /// <param name="FeeTerminalId"></param>
        /// <param name="DestTerminalId"></param>
        /// <param name="MsgContent"></param>
        /// <param name="SequenceId"></param>
        /// <param name="Service_Id"></param>
        /// <param name="FeeType"></param>
        /// <param name="FeeCode"></param>
        /// <param name="Src_Id"></param>
        /// <param name="WapURL"></param>
        /// <param name="MsgSum"></param>
        /// <param name="MsgSub"></param>
        public void Submit(ulong MsgId, uint RegisteredDelivery, uint Fee_UserType, string FeeTerminalId, string[] DestTerminalId, string MsgContent, uint SequenceId, string Service_Id, string FeeType, string FeeCode, string Src_Id, string WapURL, uint MsgSum, uint MsgSub)
        {
            CMPP_SUBMIT submit = new CMPP_SUBMIT(SequenceId)
            {
                WapURL = WapURL,
                Msg_Id = MsgId,
                Pk_total = MsgSum,
                Pk_number = MsgSub,
                Registered_Delivery = RegisteredDelivery,
                Msg_level = 1,
                Service_Id = Service_Id,
                Fee_UserType = Fee_UserType,
                Fee_terminal_Id = "",
                TP_pId = 0,
                TP_udhi = 0,
                Msg_Fmt = 8,
                Msg_src = this._Source_Addr,
                FeeType = FeeType,
                FeeCode = FeeCode,
                ValId_Time = "",
                At_Time = "",
                Src_Id = Src_Id,
                Dest_terminal_Id = DestTerminalId,
                DestUsr_tl = (uint)DestTerminalId.Length,
                Msg_Content = MsgContent,
                Reserve = ""
            };
 
            this.WriteToStreamWithLock(submit.ToBytes(), this._NetworkStream);
        }
 
        public void Suspend()
        {
            try
            {
                if (((this._ReadResponseThread != null) && (this._ReadResponseThread.ThreadState != ThreadState.Stopped)) && (this._ReadResponseThread.ThreadState != ThreadState.Suspended))
                {
                    this.OnThreadState(ThreadState.Suspended);
                    this._ReadResponseThread.Suspend();
                }
            }
            catch (Exception)
            {
            }
        }
 
        public void Terminate(uint SequenceId)
        {
            this.WriteToStreamWithLock(new MessageHeader(12, CMPP_Command_Id.CMPP_TERMINATE, SequenceId).ToBytes(), this._NetworkStream);
        }
 
        private void WriteToStreamWithLock(byte[] data, NetworkStream Stream)
        {
            try
            {
                lock (_SyncLockObject)
                {
                    if (!Stream.CanWrite) throw new Exception("Cann't Write Stream!");
                    Util.WriteToStream(data, Stream);
                }
            }
            catch (Exception exception)
            {
                this.IsConnected = false;
                this.OnError(exception.Message);
            }
        }
 
        public bool IsConnected
        {
            get
            {
                lock (this._syncIsConnectedObject)
                {
                    return this._IsConnected;
                }
            }
            set
            {
                lock (this._syncIsConnectedObject)
                {
                    this._IsConnected = value;
                }
            }
        }
 
        public delegate void MsgEventDelegate(string msg);
 
        public delegate void ThreadStateDelegate(object sender, ThreadState state);
    }
}