TCP Listener Get HANG

rudalboy09

Member
Joined
Nov 27, 2014
Messages
15
Programming Experience
1-3
i want to develop about tcp connection but i got hang when tcplistener start.
this is the code, when i push button :
                IPAddress ip = IPAddress.Parse("192.168.43.222");
                TcpListener listen = new TcpListener(ip, 8001);
                listen.Start();
                byte[] data = new byte[1024];
                int receivedDataLength;
                TcpClient client = listen.AcceptTcpClient();
                NetworkStream ns = client.GetStream();
                string welcome = "Success";
                data = Encoding.ASCII.GetBytes(welcome);
                ns.Write(data, 0, data.Length);
                while (true)
                {
                    data = new byte[1024];
                    receivedDataLength = ns.Read(data, 0, data.Length);
                    txtfromandroid.Text = Encoding.ASCII.GetString(data, 0, receivedDataLength);
                    ns.Write(data, 0, receivedDataLength);
                }
                ns.Close();
                client.Close();
                listen.Stop();

i got message "Success" on my android, but windows form was hang when i push that button.


and i use different step
                IPAddress ip = IPAddress.Parse("192.168.43.222");
                TcpListener listen = new TcpListener(ip, 8001);
                listen.Start();
                Socket s = listen.AcceptSocket();
                labelip.Text = s.RemoteEndPoint.ToString();
                byte[] terima = new byte[256];
                s.Receive(terima);
                string result = System.Text.Encoding.UTF8.GetString(terima);
                txtfromandroid.Text = result.ToString();
                string kirim = "Success";
                byte[] kirimarray = Encoding.ASCII.GetBytes(kirim);
                s.Send(kirimarray);

this is success but, i have a problem again. i can send any word, and then "Success" / kirim was received in my android.
but i can't receive or send again, i must closed and open again.

any suggest, especially the first program.
 
Last edited by a moderator:
You are calling synchronous Accept methods so they will block until a connection is accepted. You would need to either call synchronous methods on a secondary thread or else call asynchronous methods. While the code is VB, you might like to check out this example of asynchronous TCP that I created some time ago:

Asynchronous TcpListener & TcpClient
 
Back
Top Bottom