rossmann-engineering / EasyModbusTCP.NET

Modbus TCP, Modbus UDP and Modbus RTU client/server library for .NET implementations
922 stars 396 forks source link

Unable to catch IOException from ModbusServer #67

Open JohannChx opened 3 years ago

JohannChx commented 3 years ago

Hi,

How can I catch the IOException when the COM port is not existing or not available ? The following app is stopped by an unhandled System.IO.IOException that I cannot handle.

Thanks !

Jo

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                EasyModbus.ModbusServer server = new EasyModbus.ModbusServer();

                server.SerialPort = "COM3";
                server.Baudrate = 9600;
                server.Parity = System.IO.Ports.Parity.None;
                server.StopBits = System.IO.Ports.StopBits.One;

                server.Listen();

                Console.WriteLine("[ENTER] to stop server ...");
                Console.ReadLine();
            }

            catch (Exception e)
            {
                Console.WriteLine("Catch me if you can ...");
            }
        }
    }
C:\TestRTUServer\TestRTUServer\bin\Debug>TestRTUServer.exe
[ENTER] to stop server ...

Exception non gérée : System.IO.IOException: Le port 'COM3' n'existe pas.
   à System.IO.Ports.InternalResources.WinIOError(Int32 errorCode, String str)
   à System.IO.Ports.SerialStream..ctor(String portName, Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Int32 readTimeout, Int32 writeTimeout, Handshake handshake, Boolean dtrEnable, Boolean rtsEnable, Boolean discardNull, Byte parityReplace)
   à System.IO.Ports.SerialPort.Open()
   à EasyModbus.ModbusServer.ListenerThread()
   à System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   à System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   à System.Threading.ThreadHelper.ThreadStart()

C:\TestRTUServer\TestRTUServer\bin\Debug>