잊지 않겠습니다.

'socket'에 해당되는 글 2건

  1. 2010.01.05 0010. CSSocketClient
  2. 2010.01.05 0009. CSSocketServer
Client 소스는 좀더 간단하다. Server의 경우에는 Bind와 Listen의 절차를 거치고, Listen에서 BeginListen, EndListen으로
AsyncCallback을 통해야지 되지만, Client의 경우에는 간단히 Connect만으로 가능하고, 하나의 Client에서는 역시 하나의
연결정도만 신경을 쓰면 되기 때문에 더욱더 편한 개발이 가능하다.

솔찍한 생각으로 예제 소스이긴 하지만, UI단만 조금 붙여버리면 거의 일반 프로그램들과 큰 차이가 안보인다.
Socket의 Close시에 Shutdown으로 Socket을 정리하는 부분에 신경을 쓰면 될 것 같다.


001./****************************** Module Header ******************************\
002.* Module Name:  Program.cs
003.* Project:      CSSocketClient
004.* Copyright (c) Microsoft Corporation.
005.*
006.* Sockets are an application programming interface(API) in an operating system
007.* used for in inter-process communication. Sockets constitute a mechanism for
008.* delivering incoming data packets to the appropriate application process or
009.* thread, based on a combination of local and remote IP addresses and port
010.* numbers. Each socket is mapped by the operational system to a communicating
011.* application process or thread.
012.*
013.*
014.* .NET supplies a Socket class which implements the Berkeley sockets interface.
015.* It provides a rich set of methods and properties for network communications.
016.* Socket class allows you to perform both synchronous and asynchronous data
017.* transfer using any of the communication protocols listed in the ProtocolType
018.* enumeration. It supplies the following types of socket:
019.*
020.* Stream: Supports reliable, two-way, connection-based byte streams without
021.* the duplication of data and without preservation of boundaries.
022.*
023.* Dgram:Supports datagrams, which are connectionless, unreliable messages of
024.* a fixed (typically small) maximum length.
025.*
026.* Raw: Supports access to the underlying transport protocol.Using the
027.* SocketTypeRaw, you can communicate using protocols like Internet Control
028.* Message Protocol (Icmp) and Internet Group Management Protocol (Igmp).
029.*
030.* Rdm: Supports connectionless, message-oriented, reliably delivered messages,
031.* and preserves message boundaries in data.
032.*
033.* Seqpacket:Provides connection-oriented and reliable two-way transfer of
034.* ordered byte streams across a network.
035.*
036.* Unknown:Specifies an unknown Socket type.
037.*
038.* This source is subject to the Microsoft Public License.
040.* All other rights reserved.
041.*
042.* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
043.* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
044.* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
045.\***************************************************************************/
046. 
047.#region Using directives
048.using System;
049.using System.Collections.Generic;
050.using System.Linq;
051.using System.Text;
052.using System.Net;
053.using System.Net.Sockets;
054.using System.Security;
055.using System.Security.Permissions;
056.#endregion
057. 
058. 
059.public class Program
060.{
061.    static void Main(string[] args)
062.    {
063.        // Receiving byte array
064.        byte[] bytes = new byte[1024];
065.        try
066.        {
067.            // Create one SocketPermission for socket access restrictions
068.            SocketPermission permission = new SocketPermission(
069.                NetworkAccess.Connect,    // Connection permission
070.                TransportType.Tcp,        // Defines transport types
071.                "",                       // Gets the IP addresses
072.                SocketPermission.AllPorts // All ports
073.                );
074. 
075.            // Ensures the code to have permission to access a Socket
076.            permission.Demand();
077. 
078.            // Resolves a host name to an IPHostEntry instance          
079.            IPHostEntry ipHost = Dns.GetHostEntry("");
080. 
081.            // Gets first IP address associated with a localhost
082.            IPAddress ipAddr = ipHost.AddressList[0];
083. 
084.            // Creates a network endpoint
085.            IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 6000);
086. 
087.            // Create one Socket object to setup Tcp connection
088.            Socket sender = new Socket(
089.                ipAddr.AddressFamily,// Specifies the addressing scheme
090.                SocketType.Stream,   // The type of socket
091.                ProtocolType.Tcp     // Specifies the protocols
092.                );
093. 
094.            sender.NoDelay = true;   // Using the Nagle algorithm
095. 
096.            // Establishes a connection to a remote host
097.            sender.Connect(ipEndPoint);
098.            Console.WriteLine("Socket connected to {0}",
099.                sender.RemoteEndPoint.ToString());
100. 
101.            // Sending message
102.            //<client quit=""> is the sign for end of data
103.            string theMessage = "Hello World!";
104.            byte[] msg =
105.                Encoding.Unicode.GetBytes(theMessage +"<client quit="">");
106. 
107.            // Sends data to a connected Socket.
108.            int bytesSend = sender.Send(msg);
109. 
110.            // Receives data from a bound Socket.
111.            int bytesRec = sender.Receive(bytes);
112. 
113.            // Converts byte array to string
114.            theMessage = Encoding.Unicode.GetString(bytes, 0, bytesRec);
115. 
116.            // Continues to read the data till data isn't available
117.            while (sender.Available > 0)
118.            {
119.                bytesRec = sender.Receive(bytes);
120.                theMessage += Encoding.Unicode.GetString(bytes, 0, bytesRec);
121.            }
122.            Console.WriteLine("The server reply: {0}", theMessage);
123. 
124.            // Disables sends and receives on a Socket.
125.            sender.Shutdown(SocketShutdown.Both);
126. 
127.            //Closes the Socket connection and releases all resources
128.            sender.Close();
129.        }
130.        catch (Exception ex)
131.        {
132.            Console.WriteLine("Exception: {0}", ex.ToString());
133.        }
134.    }
135.}
136.</client></client>
Posted by Y2K
,
Socket을 사용해서 TCP/IP 서버를 만들게 되면 개발에서 가장 신경쓰게 되는 것이 Multi-Thread 문제이다.
이부분에 대해서 .NET에서 내놓은 최고의 Solution은 IAsyncCallback interface를 이용해서 BeginXXX 와
EndXXX를 이용하는 방법이다. 이 방법은 WebService client, Stream, Socket 등 데이터를 읽고, 쓰는데에
시간이 소요가 되어 Multi-Thread를 구현해야지 되는 거의 모든 경우에서 사용이 가능하다.

예제 소스는 다음과 같다. IPV6를 사용하는 소스를 IPV4로만 변경시킨 예제이다.


001./****************************** Module Header ******************************\
002.* Module Name:  Program.cs
003.* Project:      CSSocketServer
004.* Copyright (c) Microsoft Corporation.
005.*
006.* Sockets are an application programming interface(API) in an operating system
007.* used for in inter-process communication. Sockets constitute a mechanism for
008.* delivering incoming data packets to the appropriate application process or
009.* thread, based on a combination of local and remote IP addresses and port
010.* numbers. Each socket is mapped by the operational system to a communicating
011.* application process or thread.
012.*
013.*
014.* .NET supplies a Socket class which implements the Berkeley sockets interface.
015.* It provides a rich set of methods and properties for network communications.
016.* Socket class allows you to perform both synchronous and asynchronous data
017.* transfer using any of the communication protocols listed in the ProtocolType
018.* enumeration. It supplies the following types of socket:
019.*
020.* Stream: Supports reliable, two-way, connection-based byte streams without
021.* the duplication of data and without preservation of boundaries.
022.*
023.* Dgram:Supports datagrams, which are connectionless, unreliable messages of
024.* a fixed (typically small) maximum length.
025.*
026.* Raw: Supports access to the underlying transport protocol.Using the
027.* SocketTypeRaw, you can communicate using protocols like Internet Control
028.* Message Protocol (Icmp) and Internet Group Management Protocol (Igmp).
029.*
030.* Rdm: Supports connectionless, message-oriented, reliably delivered messages,
031.* and preserves message boundaries in data.
032.*
033.* Seqpacket:Provides connection-oriented and reliable two-way transfer of
034.* ordered byte streams across a network.
035.*
036.* Unknown:Specifies an unknown Socket type.
037.*
038.* This source is subject to the Microsoft Public License.
040.* All other rights reserved.
041.*
042.* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
043.* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
044.* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
045.\***************************************************************************/
046. 
047.#region Using Directive
048.using System;
049.using System.Collections.Generic;
050.using System.Linq;
051.using System.Text;
052.using System.Net;
053.using System.Net.Sockets;
054.using System.Threading;
055.using System.Security;
056.using System.Security.Permissions;
057.#endregion
058. 
059. 
060.public class Program
061.{
062.    static void Main(string[] args)
063.    {
064.        // Creates one SocketPermission object for access restrictions
065.        SocketPermission permission = new SocketPermission(
066.            NetworkAccess.Accept,     // Allowed to accept connections
067.            TransportType.Tcp,        // Defines transport types
068.            "",                       // The IP addresses of local host
069.            SocketPermission.AllPorts // Specifies all ports
070.            );
071. 
072.        // Listening Socket object
073.        Socket sListener = null;
074. 
075.        try
076.        {
077.            // Ensures the code to have permission to access a Socket
078.            permission.Demand();
079. 
080.            // Resolves a host name to an IPHostEntry instance
081.            IPHostEntry ipHost = Dns.GetHostEntry("");
082. 
083.            ///Get First IPV4 Address
084.            ///아직까지는 IPV4로 만들지 않으면 외부에서 접근을 못하는 경우가 많다.;
085.            IPAddress ipAddr = ipHost.AddressList.Where(a => a.AddressFamily != AddressFamily.InterNetworkV6).First();
086. 
087.            // Creates a network endpoint
088.            IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 6000);
089. 
090.            // Create one Socket object to listen the incoming connection
091.            sListener = new Socket(
092.                ipAddr.AddressFamily,
093.                SocketType.Stream,
094.                ProtocolType.Tcp
095.                );
096. 
097.            // Associates a Socket with a local endpoint
098.            sListener.Bind(ipEndPoint);
099. 
100.            // Places a Socket in a listening state and specifies the maximum
101.            // Length of the pending connections queue
102.            sListener.Listen(10);
103. 
104.            Console.WriteLine("Waiting for a connection on port {0}",
105.                ipEndPoint);
106. 
107.            // Begins an asynchronous operation to accept an attempt
108.            AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
109.            sListener.BeginAccept(aCallback, sListener);
110.        }
111.        catch (Exception ex)
112.        {
113.            Console.WriteLine("Exception: {0}", ex.ToString());
114.            return;
115.        }
116. 
117.        Console.WriteLine("Press the Enter key to exit ...");
118.        Console.ReadLine();
119.         
120.        if (sListener.Connected)
121.        {
122.            sListener.Shutdown(SocketShutdown.Receive);
123.            sListener.Close();
124.        }
125.    }
126. 
127. 
128.    /// <summary>
129.    /// Asynchronously accepts an incoming connection attempt and creates
130.    /// a new Socket to handle remote host communication.
131.    /// </summary>    
132.    /// <param name="ar">the status of an asynchronous operation
133.    /// 
134.    public static void AcceptCallback(IAsyncResult ar)
135.    {
136.        Socket listener = null;
137. 
138.        // A new Socket to handle remote host communication
139.        Socket handler = null;
140.        try
141.        {
142.            // Receiving byte array
143.            byte[] buffer = new byte[1024];
144.            // Get Listening Socket object
145.            listener = (Socket)ar.AsyncState;
146.            // Create a new socket
147.            handler = listener.EndAccept(ar);
148. 
149.            // Using the Nagle algorithm
150.            handler.NoDelay = true;
151. 
152.            // Creates one object array for passing data
153.            object[] obj = new object[2];
154.            obj[0] = buffer;
155.            obj[1] = handler;
156. 
157.            // Begins to asynchronously receive data
158.            handler.BeginReceive(
159.                buffer,        // An array of type Byt for received data
160.                0,             // The zero-based position in the buffer
161.                buffer.Length, // The number of bytes to receive
162.                SocketFlags.None,// Specifies send and receive behaviors
163.                new AsyncCallback(ReceiveCallback),//An AsyncCallback delegate
164.                obj            // Specifies infomation for receive operation
165.                );
166. 
167.            // Begins an asynchronous operation to accept an attempt
168.            AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
169.            listener.BeginAccept(aCallback, listener);
170.        }
171.        catch (Exception ex)
172.        {
173.            Console.WriteLine("Exception: {0}", ex.ToString());
174.        }
175.    }
176. 
177.    /// <summary>
178.    /// Asynchronously receive data from a connected Socket.
179.    /// </summary>
180.    /// <param name="ar">
181.    /// the status of an asynchronous operation
182.    /// 
183.    public static void ReceiveCallback(IAsyncResult ar)
184.    {
185.        try
186.        {
187.            // Fetch a user-defined object that contains information
188.            object[] obj = new object[2];
189.            obj = (object[])ar.AsyncState;
190. 
191.            // Received byte array
192.            byte[] buffer = (byte[])obj[0];
193. 
194.            // A Socket to handle remote host communication.
195.            Socket handler = (Socket)obj[1];
196. 
197.            // Received message
198.            string content = string.Empty;
199. 
200.            // The number of bytes received.
201.            int bytesRead = handler.EndReceive(ar);
202. 
203.            if (bytesRead > 0)
204.            {
205.                content += Encoding.Unicode.GetString(buffer, 0,
206.                    bytesRead);
207.                // If message contains "<client quit="">", finish receiving
208.                if (content.IndexOf("<client quit="">") > -1)
209.                {
210.                    // Convert byte array to string
211.                    string str =
212.                        content.TrimEnd(("<client quit="">").ToCharArray());
213.                    Console.WriteLine(
214.                        "Read {0} bytes from client.\n Data: {1}",
215.                        str.Length, str);
216. 
217.                    // Prepare the reply message
218.                    byte[] byteData =
219.                        Encoding.Unicode.GetBytes(str);
220. 
221.                    // Sends data asynchronously to a connected Socket
222.                    handler.BeginSend(byteData, 0, byteData.Length, 0,
223.                        new AsyncCallback(SendCallback), handler);
224.                }
225.                else
226.                {
227.                    // Continues to asynchronously receive data
228.                    byte[] buffernew = new byte[1024];
229.                    obj[0] = buffernew;
230.                    obj[1] = handler;
231.                    handler.BeginReceive(buffernew, 0, buffernew.Length,
232.                        SocketFlags.None,
233.                        new AsyncCallback(ReceiveCallback), obj);
234.                }
235.            }
236.        }
237.        catch (Exception ex)
238.        {
239.            Console.WriteLine("Exception: {0}", ex.ToString());
240.        }
241.    }
242. 
243.    /// <summary>
244.    /// Sends data asynchronously to a connected Socket.
245.    /// </summary>
246.    /// <param name="ar">
247.    /// The status of an asynchronous operation
248.    /// 
249.    public static void SendCallback(IAsyncResult ar)
250.    {
251.        try
252.        {
253.            // A Socket which has sent the data to remote host
254.            Socket handler = (Socket)ar.AsyncState;
255. 
256.            // The number of bytes sent to the Socket
257.            int bytesSend = handler.EndSend(ar);
258.            Console.WriteLine(
259.                "Sent {0} bytes to Client",bytesSend);
260.        }
261.        catch (Exception ex)
262.        {
263.            Console.WriteLine("Exception: {0}", ex.ToString());
264.        }
265.    }
266.}
267.</client></client></client>
Posted by Y2K
,