Click here to Skip to main content
15,867,594 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, i found a code on the MSDN site where the server listens on a port and the client connects to it.
I have reversed the functionality,i.e. my CLIENT listens on a port and SERVER sends a request to it.
The problem that occurs after pressing the START LISTENING button . The client form simply hangs and no action takes place.
Could anyone help me understand where the problem underlies?
Thanks in advance

This the client side of code
C#
public partial class Form1 : Form
    {     
        TcpListener tcpListener = null;
        public Form1()
        {
            InitializeComponent();
            buttonDisconnect.Enabled = false;
        }
        public void createListener()
        {
            // Create an instance of the TcpListener class.
            
            IPAddress ipAddress = Dns.GetHostAddresses(Dns.GetHostName()).Where(address => address.AddressFamily == AddressFamily.InterNetwork).First();
            //MessageBox.Show(ipAddress.ToString());
            try
            {
                // Set the listener on the local IP address 
                // and specify the port.
                tcpListener = new TcpListener(ipAddress, 13);
                tcpListener.Start();
                textBox1.AppendText("Waiting for a connection...");
                btnStartListen.Enabled = false;
                buttonDisconnect.Enabled = true;
                buttonDisconnect.Visible = true;
            }
            catch (Exception e)
            {
                textBox1.AppendText("Error: " + e.ToString());
            }
            while (true)
            {
                // Always use a Sleep call in a while(true) loop 
                // to avoid locking up your CPU.
                Thread.Sleep(10);
                // Create a TCP socket. 
                // If you ran this server on the desktop, you could use 
                // Socket socket = tcpListener.AcceptSocket() 
                // for greater flexibility.
                TcpClient tcpClient = tcpListener.AcceptTcpClient();
                // Read the data stream from the client. 
                byte[] bytes = new byte[256];
                NetworkStream stream = tcpClient.GetStream();
                stream.Read(bytes, 0, bytes.Length);
                string mstrMessage = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
                textBox1.AppendText(mstrMessage);
                SocketHelper helper = new SocketHelper();
                helper.processMsg(tcpClient, stream, bytes);
            }
        }
        private void btnStartListen_Click(object sender, EventArgs e)
        {
            this.createListener();
        }
        
        private void buttonDisconnect_Click(object sender, EventArgs e)
        {
            if (buttonDisconnect.Enabled == true)
            {
                buttonDisconnect.BackColor = System.Drawing.Color.DarkBlue;
                //MessageBox.Show("OFF 1");
                try
                {
                    textBox1.AppendText("Stopping listener");
                    //MessageBox.Show("OFF 2");
                    tcpListener.Stop();
                   // MessageBox.Show("OFF 3");
                    textBox1.AppendText("stopped");
                }
                catch (Exception)
                {
                    MessageBox.Show("Unhandled Listener Close");
                }
            }
            else
                if (buttonDisconnect.Enabled == false)
                    MessageBox.Show("Error");
            
        }
    }



This the SocketHelper Class

C#
class SocketHelper
    {
        TcpClient mscClient;
        string mstrMessage;
        string mstrResponse;
        byte[] bytesSent;
        public void processMsg(TcpClient client, NetworkStream stream, byte[] bytesReceived)
        {
            // Handle the message received and  
            // send a response back to the client.
            mstrMessage = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length);
            mscClient = client;
            mstrMessage = mstrMessage.Substring(0, 5);
            if (mstrMessage.Equals("Hello"))
            {
                mstrResponse = "Goodbye";
            }
            else
            {
                mstrResponse = "What?";
            }
            bytesSent = Encoding.ASCII.GetBytes(mstrResponse);
            stream.Write(bytesSent, 0, bytesSent.Length);
        }
    }
Posted
Updated 7-May-14 19:48pm
v2

1 solution

First of all set your TCP Task in Another Thread than your current context thread. the reason of your TCP listener that stuck is no action from your server side application you or implementation.
here is one my client side code I've used to send random byte array and get some information from server and also i used thread for best result As you could see below



C#
try
         {
             tcpThread = new Thread(new ThreadStart(tcpMethod));
             tcpThread.Start();
         }
         catch (Exception)
         {

             MessageBox.Show("Error in Running Thread!");
         }

#region TCP Connection Method
        private void tcpMethod()
        {
            try
            {
                TcpClient tcpclnt = new TcpClient();
                //Connecting...
                tcpclnt.Connect("192.168.5.32", 9696);
                //Connected
                byte[] array = new byte[512];
                Random random = new Random();
                random.NextBytes(array);
                Stream stm = tcpclnt.GetStream();
                stm.Write(array, 0, array.Length);
                byte[] result = new byte[512];
                stm.Read(result, 0, 512);
                tcpclnt.Close();

            }

            catch (Exception exception)
            {
                
                MessageBox.Show("Error In reading TCP Server : " + exception.StackTrace);
            }
        }
        #endregion
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900