Synchronous - Client Socket Connection in .NET with C#

C# with .NET in Connection Socket Client - Synchronous

I wanted to use the socket functionality in .NET, so i searched and tested some examples.

The best i got, which works for me, as following:

Synchronous Client Socket Connection:

 

 public class SynchronousSocketListener
    {
        // Data buffer for incoming data.
        private static int BUFFER_SIZE = 4 * 1024;
        private readonly byte[] bytes = new byte[BUFFER_SIZE];

        private static void StartClient()
        {
            // Connect to a remote device.
            try
            {
                // Establish the remote endpoint for the socket.
                // The name of the 
                // remote device is "host.contoso.com".
                IPHostEntry ipHostInfo = Dns.GetHostEntry("Adresse");
                IPAddress ipAddress = ipHostInfo.AddressList.FirstOrDefault(
                    ip => ip.AddressFamily == AddressFamily.InterNetwork);
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

                // Create a TCP/IP socket.
                Socket client = new Socket(AddressFamily.InterNetwork, 
                    SocketType.Stream, ProtocolType.Tcp);

                string result = "";
                try
                {
                    // Encode the data string into a byte array.
                    byte[] msg = Encoding.UTF8.GetBytes(message);

                    // Send the data through the socket.
                    int bytesSent = client.Send(msg);

                    // Receive the response from the remote device.
                    int bytesRec = 0;

                    do
                    {
                        bytesRec = client.Receive(bytes, 0, 
                            client.Available, SocketFlags.None);
                        result = Encoding.UTF8.GetString(bytes, 0, bytesRec);
                    } while (client.Available > 1);
                }
                catch (ArgumentNullException ane)
                {
                    Error = "ArgumentNullException : " + ane;
                }
                catch (SocketException se)
                {
                    Error = "SocketException : " + se.ToString();
                }
                catch (Exception e)
                {
                    Error = "Unexpected exception : " + e;
                }

                // Release the socket.
                client.Shutdown(SocketShutdown.Both);
                client.Close();

                return result;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.ReadLine();
            }
        }

        static int Main(string[] args)
        {
            StartClient();
            return 0;
        }
    }


Comments are closed