Stop the asynchronous TCP application appropriately

Hi, I have a disconnect button click event in my SERVER application as follows. Before this dc, it will alert other clients by sending the "/ exit" command. After that, he will disconnect his 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 executes the Socket.BeginRecieve () method all the time. How do we declare the begin receive method to stop it from working so that I can close normally.

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);


    }
+3
source share
2 answers

You must use the IAsyncResultreturn methods BeginXXX. IIRC, you can get rid of WaitHandle.

0

, (, , - )? , , .

, , .

, :).

, , :
1) bool, (IE, , )
2) a
3) .

0

Source: https://habr.com/ru/post/1769293/


All Articles