Jan Paolo Go
Jan Paolo Go

Reputation: 6532

SocketException proper handling in C#

I'm currently writing a code in C# and it needs to communicate with a program written in VB6 through sockets. <br/> When the VB6 program is not running, my C# program throws a SocketException.
What I did was catch the exception but I noticed that it will keep throwing that exception until the VB6 program runs again.<br/><br/> The ReceiveFrom(...) method is in an infinite loop so when the VB6 program runs again, it can receive data.<br/><br/> I wonder if there's a better way to handle this.

the C# code looks like this...

internal class SocketConnection : Connection
{
    private Socket socket;
    private EndPoint localEndPoint;
    private IPEndPoint remoteIPEndPoint;

    internal SocketConnection(int localPortNumber, IPAddress remoteIPAddress, int remotePortNumber)
    {
        IPEndPoint localIPEndPoint = new IPEndPoint(
            GetLocalIPAddress(),
            localPortNumber);

        socket = new Socket(
            localIPEndPoint.Address.AddressFamily,
            SocketType.Dgram,
            ProtocolType.Udp);

        socket.Bind(localIPEndPoint);

        localEndPoint = (EndPoint)localIPEndPoint;
        Thread receiver = new Thread(() => Receive());
        receiver.Start();

        remoteIPEndPoint = new IPEndPoint(remoteIPAddress, remotePortNumber);
    }

    private void Receive()
    {
        byte[] msg = new Byte[256];
        while (true)
        {
            try
            {
                socket.ReceiveFrom(msg, ref localEndPoint);
                buffer = Encoding.ASCII.GetString(msg).TrimEnd('\0');
            }
            catch (SocketException)
            {
                buffer = string.Empty;
            }
        }
    }
    private IPAddress GetLocalIPAddress()
    {
        var host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                return ip;
            }
        }
        throw new Exception("Local IP Address Not Found!");
    }

    protected override void Interrogate(string message)
    {
        socket.SendTo(Encoding.ASCII.GetBytes(message), remoteIPEndPoint);
    }
}

Upvotes: 0

Views: 136

Answers (1)

MSE
MSE

Reputation: 345

Before calling ReceiveFrom you should check that there is something to read in the socket :

                int available = socket.Available;
                if (available > 0)
                {
                    socket.ReceiveFrom(msg, 0, Math.Min(msg.Length, available), SocketFlags.None, ref localEndPoint);
                    buffer = Encoding.ASCII.GetString(msg).TrimEnd('\0');
                }

Upvotes: 1

Related Questions