So, I am writing this school project that should be some basic chat program that consists of a client and a server. I am trying to handle either the server or the client programs being closed.
So when you press the big red X in the Client window, this is what happens:
private void Window_Closing(object sender, CancelEventArgs e)
{
Data msgToSend = new Data();
msgToSend.cmdCommand = Command.Logout;
msgToSend.strName = LoginName;
byte[] b = msgToSend.ToByte();
ClientSocket.Send(b);
}
It sends a message to the server informing it that someone is logging out, so it can remove the user from the user list, etc.
The problem occurs when the server is being closed, and it tries to send a message to the clients informing them that the server has shut down, so the clients can inform the users and then close.
So the server's message arrives, and the client program is about to close, but the code above will try to inform the server falsely about the logout, but the server is already down by this time, so there will be a whole lot of error messages.
I guess I would need some kind of an 'if' statement in the procedure above which could decide whether the code should run, but I have no idea what it should be. Ideas?
Simply check if the client is connected to the server. Both Socket
and TcpClient
classes have a Connected
property:
http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected%28v=vs.110%29.aspx http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.connected(v=vs.110).aspx
You can then do:
if (client.Connected) {
Data msgToSend = new Data();
msgToSend.cmdCommand = Command.Logout;
msgToSend.strName = LoginName;
byte[] b = msgToSend.ToByte();
ClientSocket.Send(b);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With