How can I close and then reopen async TCP socket in C#?

261 Views Asked by At

I'm middle-exp in C# and multi threated apps and I have, a problem with change port when application is runnung (I think the best way is destroy old Socket and open a brand new), but I can't do this.

Below part of my code - WindowsForm app:

    private byte[] data = new byte[1024];
    private int size = 1024;
    private Socket server;

    delegate void Delegate();


     public Form1()
    {
        InitializeComponent();
        StartServer(11000);

    }

    public void StartServer(int port)
    {
        server = new Socket(AddressFamily.InterNetwork,
              SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint iep = new IPEndPoint(IPAddress.Any, port);
        server.Bind(iep);
        server.Listen(100);
        server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

        server.BeginAccept(new AsyncCallback(AcceptConn), server);
        listbox.Items.Add("[S] Server start...");}));

    }

    void AcceptConn(IAsyncResult iar)
    {   
        Socket oldserver = (Socket)iar.AsyncState;
        Socket client = oldserver.EndAccept(iar);

        client.BeginReceive(data, 0, size, SocketFlags.None,
                          new AsyncCallback(ReceiveData), client);


    }

    void ReceiveData(IAsyncResult iar)
    {
        Socket client = (Socket)iar.AsyncState;
        int recv = client.EndReceive(iar);
        if (recv == 0)
        {
            client.Close();



            server.BeginAccept(new AsyncCallback(AcceptConn), server);
            return;
        }
        string receivedData = Encoding.ASCII.GetString(data, 0, recv);



        byte[] message2 = Encoding.ASCII.GetBytes(receivedData);

        listbox.BeginInvoke(new Delegate(() =>
        { listbox.Items.Add("[S] Rcv: " + receivedData); }));

    }

Above code works perfectly but when I want to close this Socket and open a new one I get some errors:

case 1: Error:: System.ObjectDisposedException: "Cannot access deleted object. Object name: 'System.Net.Sockets.Socket'. "

    private void change_button_Click(object sender, EventArgs e)
    {
      server.Close();
    }

case 2: ERROR: System.Net.Sockets.SocketException: "The request to send or receive data has been blocked because the socket is not connected and no address was specified when sending a datagram through the socket using a" send to "call"

    private void change_button_Click(object sender, EventArgs e)
    {
       server.Shutdown(SocketShutdown.Both);


    }

case 3: Not Error but now my app listening and handling connection on two ports and this aannot working this way.

    private void change_button_Click(object sender, EventArgs e)
    {
       StartServer(22000);
    }

Can somebody help me to understand why I cannot close a created async TCP Socket? Thank U!

0

There are 0 best solutions below