Handle exception with a failed tcp connection in c# .NET - c#

i'm trying to handle the exception of a failed tcp connection, but i don't know how exactly do it. I need it when it's impossible to connect to the server and i would a simple Message box that says the it's impossible to contact the server and than the program return to the main form.
public Connessione(string Hostname, int Port)
{
try
{
tcpSocket = new TcpClient(Hostname, Port);
}
catch
{
show the message box and go back to the main form
}
}
this is the part of the code. i would ask you also a good guide about how to handle exception. thank you so much!!

In the catch statement you can get the exception thrown like this (or anything similar):
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Also, if you do not catch the exception (or throw a new one), any code calling the Connessione method can catch the exception like this:
void FirstMethod()
{
try
{
Connessione("google.com", 80);
}
catch (Exception ex)
{
MessageBox.Show("Could not connect to server: " + ex.Message);
}
}
public void Connessione(string hostname, int port)
{
TcpClient tcpSocket = new TcpClient(hostname, port);
// ... Doing things with tcpSocket
}
This is a great article going through how exceptions work and how to use them properly:
https://stackify.com/csharp-exception-handling-best-practices/?utm_referrer=https%3A%2F%2Fduckduckgo.com%2F

Related

udpclient.receive() suddenly stops receiving

I'm using UdpClient to receive data from a single host(actually it's a microcontroller that sends 32 bytes of data every 4 milliseconds.
The program I wrote is pretty simple.
I'm initializing the UdpClient like this(in Program.cs):
public static UdpClient client = new UdpClient(1414);
after that i do this in Form_Load event:
static UdpClient client = Program.client;
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
and then call the client.Recieve() like this:
Task.Run(() =>
{
while (true)
{
try
{
data = client.Receive(ref RemoteIpEndPoint);
}
catch (Exception ex)
{
String err_type = ex.GetType().Name;
if (err_type == "SocketException")
{
MessageBox.Show("Cannot Find The Device.", "Device Error.");
}
}
}
});
the program runs fine on my own system (using Windows 10). However when i run this program on windows 7,at random times,but with 100% chance client.Recieve() stops working and the program no longer receives any data. no exception is thrown. to find the root of the problem, I installed Wireshark to test if there is any incoming data.The answer was no(the LAN port light stops blinking too) . What has me confused is that this does not happen on windows 10.
The thing is, you miss all exceptions except SocketException.
To find out, what's going on, please, rewrite your catch block:
Task.Run(() =>
{
while (true)
{
try
{
data = client.Receive(ref RemoteIpEndPoint);
}
catch (SocketException ex)
{
MessageBox.Show("Cannot Find The Device.", "Device Error.");
}
catch (Exception e)
{
MessageBox.Show(e.GetType().Name, e.Message);
}
}
});
Turns out my code was completely fine.
This was a hardware problem on our side.

error 1503 the service didn't respond to the start or control request in a timely fashion

I have installed a Windows Service for my project, this error pop out when I start the service.
error 1503 the service didn't respond to the start or control request in a timely fashion
However, this project works fine when I debug in Visual Studio Code but when I use Visual Studio 2017 to create and start the service by following this tutorial and
Few solution I tried but the error still the same. Here are the solution I have tried.
Use CCCleaner to scan and fix issues
Modify ServicesPipeTimeout to 180000
The Logservice below can write the String into a text file, where I analyze the service run up until which part then fails. The service only able to run until LogService("3"); then it fails at receive the bytes from port.
Here is the code:
public Service1()
{
InitializeComponent();
LogService("server");
try
{
LogService("1");
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
UdpClient udpListener = new UdpClient(514);
byte[] bReceive; string sReceive; string sourceIP;
Console.WriteLine("Waiting...");
/* Main Loop */
/* Listen for incoming data on udp port 514 (default for SysLog events) */
while (true)
{
LogService("2");
try
{
LogService("3");
bReceive = udpListener.Receive(ref anyIP);
LogService("4");
/* Convert incoming data from bytes to ASCII */
sReceive = Encoding.ASCII.GetString(bReceive);
LogService(sReceive);
/* Get the IP of the device sending the syslog */
sourceIP = anyIP.Address.ToString();
LogService("5");
LogService(sourceIP);
new Thread(new logHandler(sourceIP, sReceive).handleLog).Start();
/* Start a new thread to handle received syslog event */
LogService(sReceive);
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
throw ex;
}
}
I'm not sure if the error is occur because of the codes or other reasons
Update
Refer to this post, I tried to turn off the firewall to receive all the connection, but the error still remain the same.
There was once my project successfully listen the data from the server after I add udpListener.Client.Bind(anyIP); into the code, but then after some modification it is not functioning again. I'm not sure is the Bind() make the code works even just for once.
This is the way I solve my error refer to this post. Anyway, I'm not completely understand the process behind this, if anyone have some good example or link in explaining this solution please don't hesitate to comment below.
protected override void OnStart(string[] args)
{
LogService("Service started");
NewThread = new Thread(runSysLog);
NewThread.Start();
}
protected override void OnStop()
{
LogService("Service stopped");
StopRequest.Set();
//NewThread.Join();
}
public void runSysLog()
{
try
{
AutoResetEvent StopRequest = new AutoResetEvent(false);
/* Main Loop */
while (true)
{
if (StopRequest.WaitOne(5000)) return;
try
{
//while (udpListener.Available > 0)
if (udpListener.Available > 0)
{
//Some code here
}
}
catch (Exception ex)
{
LogService("Whileloop exception: " +ex.ToString());
throw ex;
}
}
}
catch (Exception ex)
{
LogService("Run Sys Log Exception: " +ex.ToString());
throw ex;
}
}

Invalid Pointer Address error attempting to connect to TCP Socket

I have the following .NET code. Most of it was written long before I was hired, and none of the original devs still work for us.
private void SendTCPMessage(string IpAddress, string Message)
{
...
//original code that fails because the Host entry produced
//has no elements in AddressList.
//IPHostEntry remoteMachineInfo = Dns.GetHostEntry(IpAddress);
//New code that fails when connecting
IPHostEntry remoteMachineInfo;
try
{
remoteMachineInfo = Dns.GetHostEntry(IpAddress);
if (remoteMachineInfo.AddressList.Length == 0)
remoteMachineInfo.AddressList =
new[]
{
new IPAddress(
//Parse the string into the byte array needed by the constructor;
//I double-checked that the correct address is produced
IpAddress.Split('.')
.Select(s => byte.Parse(s))
.ToArray())
};
}
catch (Exception)
{
//caught and displayed in a status textbox
throw new Exception(String.Format("Could not resolve or parse remote host {0} into valid IP address", IpAddress));
}
socketClient.Connect(remoteMachineInfo, 12345, ProtocolType.Tcp);
...
}
The SocketClient code of note is as follows:
public void Connect(IPHostEntry serverHostEntry, int serverPort, ProtocolType socketProtocol)
{
//this line was causing the original error;
//now AddressList always has at least one element.
m_serverAddress = serverHostEntry.AddressList[0];
m_serverPort = serverPort;
m_socketProtocol = socketProtocol;
Connect();
}
...
public void Connect()
{
try
{
Disconnect();
SocketConnect();
}
catch (Exception exception) ...
}
...
private void SocketConnect()
{
try
{
if (SetupLocalSocket())
{
IPEndPoint serverEndpoint = new IPEndPoint(m_serverAddress, m_serverPort);
//This line is the new point of failure
socket.Connect(serverEndpoint);
...
}
else
{
throw new Exception("Could not connect!");
}
}
...
catch (SocketException se)
{
throw new Exception(se.Message);
}
...
}
...
private bool SetupLocalSocket()
{
bool return_value = false;
try
{
IPEndPoint myEndpoint = new IPEndPoint(m_localAddress, 0);
socket = new Socket(myEndpoint.Address.AddressFamily, SocketType.Stream, m_socketProtocol);
return_value = true;
}
catch (SocketException)
{
return_value = false;
}
catch (Exception)
{
return_value = false;
}
return return_value;
}
When connecting to the endpoint within SocketConnect, I get a SocketException stating:
The system detected an invalid pointer address in attempting to use a pointer argument in a call.
Information online is a bit light on how to fix this. AFAICT, the address is parsing properly, and it's retrieved properly once passed in to the SocketClient class. Honestly, I don't know if this code has ever worked; I have never personally seen it do what it's supposed to, and the functionality that uses all this was created for the benefit of a single client of ours, and has apparently not been functional since before I was hired.
I need to know what to look for to resolve the error. If it helps, the remote computer to which I am trying to establish a connection is on the remote side of a VPN tunnel, and we do have connectivity via other pieces of software we use.
Help?
Found it. The address used as the local endpoint for the socket, in SetupLocalSocket(), used a similarly naive method of getting the address; by resolving the local host and getting the first address. That first address, more often than not, is an IPv6 address, not the IPv4 address that was obviously expected. So, I had it look for the first IPv4 address in the list and use that as the endpoint, and it worked.

TCP listener start exception in C#

I create a TCP listener by using the code below:
TCPListener = new TcpListener(IPAddress.Any, 1234);
I start to listen TCP devices by using the code below:
TCPListener.Start();
But here, i don't control if the port is in use. When the port is in use, program gives an exception: "Only one usage of each socket address (protocol/network address/port) is normally permitted.".
How do i handle this exception? I want to warn user that the port is in use.
Put a try/catch block around TCPListener.Start(); and catch SocketException. Also if you are opening multiple connections from your program, then its better if you keep track of your connections in a list and before opening a connection see if you already have a connection opened
It's not a good idea to get an exception to check whether the port is in use or not. Use the IPGlobalProperties object to get to an array of TcpConnectionInformation objects, which you can then interrogate about endpoint IP and port.
int port = 1234; //<--- This is your value
bool isAvailable = true;
// Evaluate current system tcp connections. This is the same information provided
// by the netstat command line application, just in .Net strongly-typed object
// form. We will look through the list, and if our port we would like to use
// in our TcpClient is occupied, we will set isAvailable to false.
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
foreach (TcpConnectionInformation tcpi in tcpConnInfoArray)
{
if (tcpi.LocalEndPoint.Port==port)
{
isAvailable = false;
break;
}
}
// At this point, if isAvailable is true, we can proceed accordingly.
For details please read this.
For handling the exception you will use try/catch as habib suggested
try
{
TCPListener.Start();
}
catch(SocketException ex)
{
...
}
Catch it and display your own error message.
Check the exception type and use this type in catch clause.
try
{
TCPListener.Start();
}
catch(SocketException)
{
// Your handling goes here
}
Put it in a try catch block.
try {
TCPListener = new TcpListener(IPAddress.Any, 1234);
TCPListener.Start();
} catch (SocketException e) {
// Error handling routine
Console.WriteLine( e.ToString());
}
Use try-catch blocks and catch the SocketException.
try
{
//Code here
}
catch (SocketException ex)
{
//Handle exception here
}
Well, considering that you're talking about exceptional situation, just handle that exception with suitable try/catch block, and inform a user about a fact.

EndConnect Exception

I'm trying to connect to a server using BeginConnect and when I specified an incorrect IpAddress or Port I get a SocketException.
The problem is that my try/catch doesn't catch the Exception:
private void OnConnect(IAsyncResult result)
{
try
{
socket.EndConnect(result);
status = Status.WaitAck;
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, onDataReady, null);
}
catch (Exception ex)
{
if (ConnectionError != null)
ConnectionError(this, new OpenWebNetErrorEventArgs(ex));
}
}
When I call the socket.EndConnect method VS report me the exception and block the program...
How can I handle it?
Thanks
Federico
Are you running the program under debugger? If so, you either have VS to break on any exception being thrown, or break on the SocketException being thrown.
If you fix that (uncheck the "thrown" column for that exception) and it should allow your Catch handler to execute.

Categories

Resources