천호석
2023-05-15 0de38c0ebeb49d545ae1d2267f2b932392bd583c
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.Collections;
using System.Net;
using System.Text;
using System.Threading;
using System.Net.Sockets;
 
namespace SA_LTT.Base
{
    public class SocketClient
    {
        #region Property
        /// <summary>
        /// Client socket
        /// </summary>
        private Socket sock;
 
        /// <summary>
        /// Receive event handler
        /// </summary>
        private ReceiveEventHandler RecevedHandler;
 
        /// <summary>
        /// Server ip to be connected
        /// </summary>
        public IPAddress Ip { get; private set; }
 
        /// <summary>
        /// Server port to be connected
        /// </summary>
        public int Port { get; private set; }
 
        /// <summary>
        /// Client name
        /// </summary>
        public string Name { get; private set; }
 
        public bool isConnected { get { return sock == null ? false : sock.Connected; } }
        #endregion
 
        #region Construct
        /// <summary>
        /// Socket client construct
        /// </summary>
        /// <param name="ip"> Server ip to be connected</param>
        /// <param name="port"> Server port to be connected</param>
        public SocketClient()
        {
            this.Ip = IPAddress.Parse("127.0.0.1");
            this.Port = 8000;
            this.Name = string.Empty;
 
            RecevedHandler = new ReceiveEventHandler();
        }
        #endregion
 
        #region Fuction
        public void ChangeAddress(IPAddress ip, int port)
        {
            if (isConnected)
            {
                Disconnect();
            }
 
            this.Ip = ip;
            this.Port = port;
        }
 
        /// <summary>
        /// Connect to server
        /// </summary>
        /// <returns></returns>
        public bool Connect()
        {
            try
            {
                if (sock == null)
                    sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                else if (sock.Connected)
                    throw new Exception("socket is already connected.");
                else
                {
                    sock.Close();
                    sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                }
 
                IPEndPoint ipep = new IPEndPoint(Ip, Port);
 
                IAsyncResult async_result = sock.BeginConnect(ipep, new AsyncCallback(ConnectedCallback), sock);
 
                if (async_result.AsyncWaitHandle.WaitOne(5000, false))
                {
                    return true;
                }
                else
                {
                    sock.Close();
                    sock = null;
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
 
        }
 
        /// <summary>
        /// Add received Event
        /// </summary>
        /// <param name="Received_event">Received event</param>
        /// <returns></returns>
        public bool Add_received_event(ReceivedEvent Received_event)
        {
            try
            {
                RecevedHandler.ReceiveEvent += Received_event;
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
 
        /// <summary>
        /// Disconnect to server
        /// </summary>
        public void Disconnect()
        {
            try
            {
                if (sock == null)
                    throw new Exception("socket is already disconnected");
 
                this.sock.Close();
 
                sock.Dispose();
                sock = null;
            }
            catch (Exception ex)
            {
            }
        }
 
        /// <summary>
        /// Async connected call back
        /// </summary>
        /// <param name="ar"></param>
        private void ConnectedCallback(IAsyncResult ar)
        {
            try
            {
                Socket client = (Socket)ar.AsyncState;
 
                if (!client.Connected) return;
 
                client.EndConnect(ar);
                sock = client;
 
                StateObject so = new StateObject(sock);
 
                so.workSocket.BeginReceive(so.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(RecieveCallback), so);
            }
            catch (Exception ex)
            {
            }
        }
 
        /// <summary>
        /// Async receieve call back
        /// </summary>
        /// <param name="ar"></param>
        private void RecieveCallback(IAsyncResult ar)
        {
            try
            {
                StateObject so = (StateObject)ar.AsyncState;
 
                if (!so.workSocket.Connected) return;
 
                int byteread = so.workSocket.EndReceive(ar);
 
                if (byteread > 0)
                {
                    so.Received_data.Append(Encoding.ASCII.GetString(so.buffer, 0, byteread));
                    RecevedHandler.OnReceived(so);
                    StateObject so2 = new StateObject(so.workSocket);
                    so.workSocket.BeginReceive(so2.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(RecieveCallback), so2);
                }
            }
            catch (Exception ex)
            {
            }
        }
 
        /// <summary>
        /// Send data
        /// </summary>
        /// <param name="data"></param>
        /// <param name="clientid"></param>
        /// <param name="sock"></param>
        public bool SendData(string data)
        {
            try
            {
                byte[] buffer = Encoding.Default.GetBytes(data);
                sock.BeginSend(buffer, 0, buffer.Length, 0, new AsyncCallback(SendCallback), sock);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
 
        /// <summary>
        /// Send data
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool SendData(byte[] data)
        {
            try
            {
                sock.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), sock);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
 
        /// <summary>
        /// Async Send call back
        /// </summary>
        /// <param name="ar"></param>
        public void SendCallback(IAsyncResult ar)
        {
            try
            {
                Socket sock = (Socket)ar.AsyncState;
 
                int byteSent = sock.EndSend(ar);
            }
            catch (Exception ex)
            {
            }
        }
        #endregion
    }
 
    public delegate void ReceivedEvent(object obj, ReceiveEventArgs e);
 
    public class ReceiveEventHandler
    {
        /// <summary>
        /// Recevied event
        /// </summary>
        public event ReceivedEvent ReceiveEvent;
 
        /// <summary>
        /// Invoke an ReceiveEvent
        /// </summary>
        /// <param name="so">StateObject after received</param>
        public virtual void OnReceived(StateObject so)
        {
            if (ReceiveEvent != null)
            {
                ReceiveEvent(this, new ReceiveEventArgs(so));
            }
        }
    }
 
    public class ReceiveEventArgs : EventArgs
    {
        public StateObject stateobject { get; private set; }
 
        /// <summary>
        /// Socket이 Received 되었을때 사용
        /// </summary>
        /// <param name="so">Received 된 후의 StateObject 값</param>
        public ReceiveEventArgs(StateObject stateobject)
        {
            this.stateobject = stateobject;
        }
    }
 
    public class StateObject
    {
        /// <summary>
        /// Received Sockect
        /// </summary>
        public Socket workSocket = null;
 
        /// <summary>
        /// Maximum size that can be received
        /// </summary>
        public const int BufferSize = 256;
 
        /// <summary>
        /// Received buffer
        /// </summary>
        public byte[] buffer = new byte[BufferSize];
 
        /// <summary>
        /// Received data string
        /// </summary>
        public StringBuilder Received_data = new StringBuilder();
 
        public StateObject(Socket sock)
        {
            workSocket = sock;
        }
    }
}