I have a client that connects to my server, now with the following code the connection happens. But if the connection can't be made an event is created so my main program can show a message if it fails. But this event isn't triggered. How can I correct my code to make this happen?
Wrapper class for my Client Socket
public class ClientWrapper
{
Socket clientSocket;
public delegate void ErrorMessageHandler(string errorMsg);
public event ErrorMessageHandler OnErrorRecieved;
public ClientWrapper(IPAddress serverIP, int port)
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(serverIP, port));
}
catch (Exception e)
{
if (OnErrorRecieved != null)
OnErrorRecieved(e.Message);
}
}
}
In my program code, Where the event is used
//Connect to Server
ClientWrapper clientSocket = new ClientWrapper(serverIP, port);
//Event trigger if client fails to connect to server
clientSocket.OnErrorRecieved += new ClientWrapper.ErrorMessageHandler(clientSocket_OnErrorRecieved);
And the method for the event
void clientSocket_OnErrorRecieved(string errorMsg)
{
MessageBox.Show("No response from server. This can be caused if Server is offline or incorrect detail is provided.", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}