Calling Socket.Accept() Returns Type initialization error

157 Views Asked by At

I am creating a simple networking application that allows one client to connect to the host and sends and recieves data between the two in a while loop. I got most of my code from MSDN, however when I run it, right after Socket.Accept() is called, the form stops running and a TypeInitialization Error is raised. Here is my code:

public static void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new byte[1024];
        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, HostingPort);

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

        // Bind the socket to the local endpoint and 
        // listen for incoming connections.
        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(10);
            Socket handler = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Start listening for connections.
            while (true)
            {
                Console.WriteLine("Waiting for a connection...");
                // Program is suspended while waiting for an incoming connection.
                handler = listener.Accept();

                // An incoming connection needs to be processed.
                while (true)
                {
                    bytes = new byte[1024];
                    int bytesRec = handler.Receive(bytes);
                    byte[] trimmedData = new byte[bytesRec];
                    Array.Copy(bytes, trimmedData, bytesRec);
                    string data = Encoding.ASCII.GetString(bytes));

                    // Show the data on the console.
                    Console.WriteLine("Text received : {0}", data);

                    // Echo the data back to the client.
                    byte[] msg = Encoding.ASCII.GetBytes(foo);

                    handler.Send(msg);
                }

                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }

        }

        catch (Exception) { }
    } 

This is the function that controls everything. Can you find the error, or if there is a proven way to complete this, I'm fine with starting over from scratch. Thank you in advance.

0

There are 0 best solutions below