1 Pluspunkt 0 Minuspunkte

Wie kann ich diesen Server ordentlich beenden ohne das eine Exception geworfen wird.

public class UDPServer<T>
{
    private UdpClient udpServer;

    private int port;

    private Thread receiveThread;

    private bool running;

    public event Action<Message<T>> MessageReceived;

    public event Action<object> MessageReceivedError;

    public UDPServer(int _port)
    {
        port = _port;
    }

    public void Start()
    {
        udpServer = new UdpClient(port);
        receiveThread = new Thread(ReceiveData);
        running = true;
        receiveThread.Start();
    }

    public void Stop()
    {
        running = false;
        udpServer.Close();
        receiveThread.Join();
    }

    private void ReceiveData()
    {
        while (running)
        {
            IPEndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
            byte[] data = udpServer.Receive(ref clientEndPoint);
            Message<T> receivedMessage = Message<T>.FromBytes(data);
            if (receivedMessage == null)
            {
                OnMessageReceivedError(data);
            }
            else
            {
                OnMessageReceived(receivedMessage);
            }
        }
    }

    protected virtual void OnMessageReceived(Message<T> message)
    {
        this.MessageReceived?.Invoke(message);
    }

    protected virtual void OnMessageReceivedError(object packet)
    {
        this.MessageReceivedError?.Invoke(packet);
    }
}
von  

1 Antwort

0 Pluspunkte 0 Minuspunkte

Du kannst die Exception einfach abfangen.

try
{

    while (running)
    {

        IPEndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
        byte[] data = udpServer.Receive(ref clientEndPoint);

        Message<T> receivedMessage = Message<T>.FromBytes(data);

        if (receivedMessage == null)
        {
            OnMessageReceivedError(data);
        }
        else
            OnMessageReceived(receivedMessage);

    }

}
catch (SocketException e)
{
    // Prüfe die Exception
}
von (732 Punkte)