weixudong
2020-11-12 52fb8c663b1e74b2a36b79bc70a452ca73db6341
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
using Core.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using UnityEngine;
 
 
public struct SocketState
{
    public TcpClient client;
    public NetworkStream socketStream;
 
    public SocketState( TcpClient c,NetworkStream ns)
    {
        this.client = c;
        this.socketStream = ns;
    }
}
 
public class TestTcpSocket : Singleton<TestTcpSocket>
{
    private static object objlock = new object();  // ÓÃÓÚ¶àÏß³ÌËø¶¨.
    protected static TestTcpSocket instace = null;
    protected TcpClient client = null;
    protected NetworkStream socketStream = null;
    protected Byte[] byteBuffer = new byte[1024 * 1024];
    protected int MAX_READ = 1024 * 1024;
 
    // Start is called before the first frame update
    void Start()
    {
 
    }
 
    // Update is called once per frame
    void Update()
    {
 
    }
 
    public void connectTcp()
    {
        try
        {
            if( this.client == null )
            {
                this.ConnectServer("127.0.0.1", 9081);
            }
            else
            {
                // TEST WORK START:
                // ²âÊÔ·¢Ëͼòµ¥µÄÏûÏ¢µ½·þÎñÆ÷¡£
                byte[] byteSend = System.Text.Encoding.Default.GetBytes("fuckzijia");
                this.SendMessage(byteSend);
 
                byte[] intArr = new byte[8];
                for( int ti = 0;ti<8;ti ++)
                    intArr[ti] = (byte)ti;
                
                this.SendMessage(intArr);
            }
        }
        catch (Exception e)
        {
            Debug.Log("³ö´í:" + e.ToString());
        }
 
    }
 
    /// <summary>
    /// Á¬½Ó·þÎñÆ÷
    /// </summary>
    public void ConnectServer(string host, int port)
    {
        // ½¨Á¢ÐµÄÁ¬½Ó
        client = new TcpClient();
        client.SendTimeout = 1000;
        client.ReceiveTimeout = 1000;
        client.NoDelay = true;
        try
        {
            client.BeginConnect(host, port, new AsyncCallback(OnConnect), client);
        }
        catch (Exception e)
        {
            Debug.Log("Á¬½Ó³ö´í:" + e.ToString());
        }
    }
 
    void OnConnect(IAsyncResult asr)
    {
        TcpClient client = (TcpClient)asr.AsyncState;
        bool validConn = (client == this.client);
        try
        {
            // ½áÊøÒì²½Á¬½Ó
            client.EndConnect(asr);
 
            // ·Çµ±Ç°Á¬½Ó
            if (!validConn)
            {
                client.Close();
            }
 
            if (client.Connected)
            {
 
                // Òì²½¶ÁsocketÊý¾Ý
                socketStream = client.GetStream();
                socketStream.BeginRead(byteBuffer, 0, MAX_READ, new AsyncCallback(OnRead), new SocketState(client, socketStream));
                Debug.Log("Async Connect TcpServer Success.");
            }
            else
            {
                Debug.Log("client connect failed.");
            }
        }
        catch (SocketException e)
        {
            Debug.Log("Á¬½ÓÖ®ºó£¬³öÎÊÌâÁË:" + e.ToString());
        }
    }
 
    /// <summary>
    /// ¶ÁÈ¡ÏûÏ¢
    /// </summary>
    void OnRead(IAsyncResult asr)
    {
        int bytesRead = 0; // ¶ÁÈ¡µ½µÄ×Ö½Ú
        bool validConn = false; // ÊÇ·ñÊǺϷ¨µÄÁ¬½Ó
 
        Debug.Log("Read Message is Called.");
 
        SocketState socketState = (SocketState)asr.AsyncState;
        TcpClient client = socketState.client;
        if (client == null || !client.Connected)
        {
            return;
        }
        try
        {
            validConn = (client == this.client);
            NetworkStream socketStream = socketState.socketStream;
 
            // ¶ÁÈ¡×Ö½ÚÁ÷µ½»º³åÇø
            bytesRead = socketStream.EndRead(asr);
 
            if (bytesRead < 1)
            {
                if (!validConn)
                {
                    // ÒѾ­ÖØÐÂÁ¬½Ó¹ýÁË
                    socketStream.Close();
                    client.Close();
                }
                else
                {
                    // ±»¶¯¶Ï¿ªÊ±
                    // Í¨ÖªÁ¬½Ó±»¶Ï¿ª
                    //OnDisconnected(DisType.Disconnect, "bytesRead < 1");
                }
                return;
            }
 
            // ½ÓÊÜÊý¾Ý°ü£¬Ð´È뻺³åÇø
            OnReceive(byteBuffer, bytesRead);
 
            // ÔٴμàÌý·þÎñÆ÷·¢¹ýÀ´µÄÐÂÏûÏ¢
            Array.Clear(byteBuffer, 0, byteBuffer.Length);   //Çå¿ÕÊý×é
            socketStream.BeginRead(byteBuffer, 0, MAX_READ, new AsyncCallback(OnRead), socketState);
        }
        catch (Exception e)
        {
            //Log.Instance.errorFormat("read data error, connect valid:{0}", e, validConn);
            Debug.Log("³öÏÖÁËÒì³££º" + e.ToString());
            if (validConn)
            {
                // Í¨ÖªÁ¬½Ó±»¶Ï¿ª
                //OnDisconnected(DisType.Exception, e);
            }
            else
            {
                socketStream.Close();
                client.Close();
            }
        }
 
        // ¶ÔÏûÏ¢½øÐнâÂë
        if (bytesRead > 0)
        {
           // OnDecodeMessage();
        }
    }
 
    private void OnReceive(byte[] byteBuffer, int bytesRead)
    {
        //throw new NotImplementedException();
        System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
        string msgReceive = ascii.GetString(byteBuffer);
        Debug.Log("¿Í»§¶ËÊÕµ½ÏûÏ¢:" + msgReceive);
    }
 
    /// <summary>
    /// ·¢ËÍÏûÏ¢
    /// </summary>
    public bool SendMessage( byte[] barr )
    {
        try
        {
            bool ret = WriteMessage( barr );
            return ret;
        }
        catch (Exception e)
        {
            Debug.Log("·¢ËÍÏûÏ¢³ö´í:" + e.ToString() );
        }
        return false;
    }
    /// <summary>
    /// Ð´Êý¾Ý
    /// </summary>
    bool WriteMessage(byte[] message)
    {
        bool ret = true;
 
        if (null != socketStream)
        {
            socketStream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWrite), socketStream);
            ret = true;
        }
        else
        {
            Debug.Log("write data, but socket not connected");
            ret = false;
        }
 
        return ret;
    }
 
    /// <summary>
    /// ÏòÁ´½ÓдÈëÊý¾ÝÁ÷
    /// </summary>
    void OnWrite(IAsyncResult r)
    {
        NetworkStream tsocketStream = null;
        try
        {
            tsocketStream = (NetworkStream)r.AsyncState;
            socketStream.EndWrite(r);
            Debug.Log("·¢ËÍÏûÏ¢µ½·þÎñÆ÷³É¹¦.");
        }
        catch (Exception e)
        {
            if ((e is IOException) && tsocketStream == this.socketStream)
            {
                // IO Òì³£²¢ÇÒ»¹Êǵ±Ç°Á¬½Ó
                //OnDisconnected(DisType.Exception, e);
            }
        }
    }
 
    /// <summary>
    /// ¹ØÓÚÍøÂç¶ÏÏߵĴ¦Àí
    /// </summary>
    void OnDisconnected()
    {
        
    }
 
    
    // ÁíÍâÒ»¸ö±ØÐëÒª´¦ÀíµÄÊÇtcpµÄÕ³°ü£¬Õâ¸öÊDZØÐëÒª´¦ÀíµÄÄÚÈÝ
 
 
    /// <summary>
    /// ¼ì²ésocket״̬
    /// </summary>
    /// <returns><c>true</c>, if socket was checked, <c>false</c> otherwise.</returns>
    public bool CheckSocketState()
    {
        //Log.Instance.info("check socket state start");
 
        // socketÁ÷Ϊ¿Õ
        if (client == null)
        {
            return true;
        }
 
        // ²»ÔÚÁ¬½Ó״̬
        if (!client.Connected)
        {
            //Log.Instance.info("check socket state end, socket is not connected");
            return false;
        }
 
        // ÅжÏÁ¬½Ó״̬
        bool connectState = true;
        Socket socket = client.Client;
        bool blockingState = socket.Blocking;
        try
        {
            byte[] tmp = new byte[1];
 
            socket.Blocking = false;
            socket.Send(tmp, 0, 0);
            connectState = true; // ÈôSend´íÎó»áÌøÈ¥Ö´ÐÐcatchÌ壬¶ø²»»áÖ´ÐÐÆätryÌåÀïÆäÖ®ºóµÄ´úÂë
 
            //Log.Instance.info("check socket state succ");
        }
        catch (SocketException e)
        {
            //Log.Instance.warnFormat("check socket error, errorCode:{0}", e.NativeErrorCode);
 
            // 10035 == WSAEWOULDBLOCK
            if (e.NativeErrorCode.Equals(10035))
            {
                // Still Connected, but the Send would block
                connectState = true;
            }
            else
            {
                // Disconnected
                connectState = false;
            }
        }
        finally
        {
            socket.Blocking = blockingState;
        }
 
        return connectState;
    }
 
}