Receive message from async TCP client

Viewed 401

I'm creating an async TCP client using C# but I'm a bit stuck trying to receive messages from my TCP server. Seems that my Receive function is not being called, because when I send a message from my server to the client, it doesn't show in my textbox (I'm using the WriteOnLog function to do it). I'm able to send the messages just fine, I'm only having trouble receiving it. Do I need to call it inside a loop?

namespace Simple_TCP_Client
{
    public partial class Form1 : Form
    {
        public Socket _client;
        public class StateObject
        { 
            public Socket workSocket = null;
            public const int BufferSize = 256;
            public byte[] buffer = new byte[BufferSize];  
            public StringBuilder sb = new StringBuilder();
        }
        public String response = String.Empty;

        public void StartClient(IPAddress ipAddress, int portnum)
        {
            try
            {
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, portnum);
                Socket client = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                client.BeginConnect(remoteEP,
                    new AsyncCallback(ConnectCallback), client);
                _client = client;
                btn_send.Enabled = true;
                Send(client, "Hello Server!");
                Receive(client);
                WriteOnLog("Response received : " + response.ToString());
            }
            catch (Exception e)
            {
                WriteOnLog(e.ToString());
            }
        }

        void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                Socket client = (Socket)ar.AsyncState;
                client.EndConnect(ar);

                WriteOnLog("Socket connected to " +
                    client.RemoteEndPoint.ToString());

            }
            catch (Exception e)
            {
                WriteOnLog(e.ToString());
            }
        }
        void Receive(Socket client)
        {
            try
            {
                StateObject state = new StateObject();
                state.workSocket = client;
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state);
            }
            catch (Exception e)
            {
                WriteOnLog(e.ToString());
            }
        }

        void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                StateObject state = (StateObject)ar.AsyncState;
                Socket client = state.workSocket;
                int bytesRead = client.EndReceive(ar);

                if (bytesRead > 0)
                {
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReceiveCallback), state);
                }
                else
                {
                    if (state.sb.Length > 1)
                    {
                        string Response = state.sb.ToString();
                        WriteOnLog(Response);
                    }
                }
            }
            catch (Exception e)
            {
                WriteOnLog(e.ToString());
            }
        }
        void Send(Socket client, String data)
        {
            byte[] byteData = Encoding.ASCII.GetBytes(data);
            client.BeginSend(byteData, 0, byteData.Length, 0,
                new AsyncCallback(SendCallback), client);
        }

        void SendCallback(IAsyncResult ar)
        {
            try
            {
                Socket client = (Socket)ar.AsyncState;
                int bytesSent = client.EndSend(ar);
                WriteOnLog("Sent " + bytesSent + " bytes to server.");
            }
            catch (Exception e)
            {
                WriteOnLog(e.ToString());
            }
        }

        public Form1()
        {
            InitializeComponent();
            btn_send.Enabled = false;
        }
        delegate void WriteOnLogCallback(string text);
        private void WriteOnLog(string text)
        {
            if (this.listBox1.InvokeRequired)
            {
                WriteOnLogCallback d = new WriteOnLogCallback(WriteOnLog);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.listBox1.Items.Add(text);
            }
        }    
        private void btn_connect_Click(object sender, EventArgs e)
        {
            IPAddress ipAddress;
            int portNum;
            if (IPAddress.TryParse(txt_ip.Text, out ipAddress) && int.TryParse(txt_port.Text, out portNum))
            {
                StartClient(ipAddress, portNum);
                if (_client.Connected)
                {
                    btn_connect.Enabled = false;
                }
            }
            else
            {
                MessageBox.Show("Please Enter a Valid Server's IP Address and Port",
             "Invalid Address or Port", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }

        private void btn_disconnect_Click(object sender, EventArgs e)
        {
            _client.Close();
            btn_connect.Enabled = true;
        }

        private void btn_send_Click(object sender, EventArgs e)
        {
            if(_client.Connected)//(networkStream.CanWrite)
            {
                Send(_client, txt_msg.Text);
                WriteOnLog(txt_msg.Text);
                txt_msg.Clear();
            }
        }
    }
}
0 Answers
Related