How can I Release TCP/IP adresse and Port win I click on button (close connection) RRS feed

  • Question

  • When I'm tring to use TCP/IP connection for Sending same data to android device, An exception show to me:

    System.Net.Sockets.SocketException: Only one of each socket adress(Protocol/network address/ Port) is usually allowed.

    It is clear that the last connection still works, then I have tried closing TCP/IP thread by a button like this:

    by default :

            bool m_StopThread = false;

    and the thread:

     new Thread(() =>
                        Thread.CurrentThread.IsBackground = true;
                        const int PORT_NO = 7800;
                        const string SERVER_IP = "";
                        while (!m_StopThread)
                            //---listen at the specified IP and port no.---
                            IPAddress localAdd = IPAddress.Parse(SERVER_IP);
                            TcpListener listener = new TcpListener(System.Net.IPAddress.Any, PORT_NO);
                            //---incoming client connected---
                            TcpClient client = listener.AcceptTcpClient();
                            //---get the incoming data through a network stream---
                            NetworkStream nwStream = client.GetStream();
                            byte[] buffer = new byte[client.ReceiveBufferSize];
                            //---read incoming stream---
                            int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
                            //---convert the data received into a string---
                            string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                                //---write back the text to the client---
                                //nwStream.Write(buffer, 0, bytesRead);
                                byte[] msg = System.Text.Encoding.ASCII.GetBytes(m);
                                Console.WriteLine("Sending back : " + m);
                                // Send back a response.     
                                nwStream.Write(msg, 0, msg.Length);

    and the Stop button 

     private void button2_Click(object sender, EventArgs e)
                m_StopThread = true;

    Then I have to know how to release TCP / IP connect

    Thank u all 

    Thursday, October 24, 2019 2:53 PM


All replies