Hi i have a disconnect button click event in my SERVER application as follows.Before it dc, it will alert other clients by sending a "/exit" command.After that it will shutdown its connection.
private void stopButton_Click(object sender, EventArgs e)
{
byte[] exit_command = Encoding.ASCII.GetBytes("/exit");
g_server_conn.BeginSend(exit_command, 0, exit_command.Length, SocketFlags.None, new AsyncCallback(Send), g_server_conn);
g_server_conn.Shutdown(SocketShutdown.Both);
g_server_conn.Close();
}
The problem is that the server is executing Socket.BeginRecieve() method all the time. How do we tell the begin recieve method to stop its operation so that i can close properly.
private void Accept(IAsyncResult iar) {
Socket winsock = (Socket)iar.AsyncState;
g_server_conn = winsock.EndAccept(iar);
//Function that exchanges names of each other
NewClient(g_server_conn);
Socket server_conn = g_server_conn;
chat_msg = new byte[1024];
server_conn.BeginReceive(chat_msg, 0, chat_msg.Length, SocketFlags.None, new AsyncCallback(Recieve), server_conn);
}
private void Recieve(IAsyncResult iar)
{
Socket server_conn = (Socket)iar.AsyncState;
server_conn.EndReceive(iar);
//If clients shutdown connection,Server recieves /exit command
if (Encoding.ASCII.GetString(chat_msg, 0, chat_msg.Length) == "/exit")
{
g_server_conn.Shutdown(SocketShutdown.Both);
g_server_conn.Close();
return;
}
SetLabel(client_name, chatListBox);
SetLabel(Encoding.ASCII.GetString(chat_msg), chatListBox);
chat_msg = new byte[1024];
server_conn.BeginReceive(chat_msg, 0, chat_msg.Length, SocketFlags.None, new AsyncCallback(Recieve), server_conn);
}