Continuously read data from the tcp server with a specified time interval

advertisements

I need to implement tcp socket Client. We have to receive data from server tcp socket with specific time interval.If we made the connection request from client then the connection will not get disconnected .we have to receive the data whenever the server sends the data.I have tried the asynchronous client communication from MSDN website. But the Receive callback function is called within receive method.So we have to receive data from server without any interval.If the data is not received continously the connection will gone to received done and the connection disconnected.

Can anyone help me...Thanks inadvance

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.Configuration;
using System.Net;
using System.IO;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Transactions;

namespace ClientSocket
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public class StateObject
        {
            public Socket workSocket = null;
            public const int BufferSize = 5176;
            public byte[] buffer = new byte[BufferSize];
            public StringBuilder sb = new StringBuilder();

        }

        public class AsynchronousClient
        {
            public const int port = 8095;

            public static ManualResetEvent connectDone =
                new ManualResetEvent(false);
            public static ManualResetEvent sendDone =
                new ManualResetEvent(false);
            public static ManualResetEvent receiveDone =
                new ManualResetEvent(false);

            public static String response = String.Empty;

            public static void StartClient()
            {
                try
                {
                    IPAddress ipAddress = IPAddress.Parse("192.168.1.89");
                    IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

                    Socket client = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);

                    client.BeginConnect(remoteEP,
                        new AsyncCallback(ConnectCallback), client);

                    connectDone.WaitOne();
                    client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

                    //Send(client, Msg + "<EOF>");
                    //sendDone.WaitOne();

                    Receive(client);
                    receiveDone.WaitOne();

                    MessageBox.Show(response, "Final Response received");

                    //Send(client, "Data From Client" + "<EOF>");
                    //sendDone.WaitOne();

                    //client.Shutdown(SocketShutdown.Both);
                    //client.Close();
                }
                catch (SocketException e)
                {
                    MessageBox.Show(e.Message);
                }
                //finally
                //{
                //    response = string.Empty;
                //}
            }

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

                    client.EndConnect(ar);

                    MessageBox.Show(string.Concat("Socket connected to ",
                        client.RemoteEndPoint.ToString()));

                    connectDone.Set();
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            }

            public static 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)
                {
                    MessageBox.Show(e.ToString());
                }
            }

            public static void ReceiveCallback(IAsyncResult ar)
            {
                MessageBox.Show("Receivecallback");
                StateObject state = (StateObject)ar.AsyncState;
                state.sb.Clear();
                Socket client = state.workSocket;

                try
                {
                    // Read data from the remote device.
                    int bytesRead = client.EndReceive(ar);

                    if (bytesRead > 0)
                    {

                        state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
                        MessageBox.Show(state.sb.ToString(), "Data");

                        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                            new AsyncCallback(ReceiveCallback), state);
                    }
                    else
                    {
                        //if (state.sb.Length > 1)
                        //{
                        //    response = state.sb.ToString();
                        //}
                        //////Send(client, "NG", "Error");
                        //receiveDone.Set();
                        client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

                        //state.sb.Clear();
                    }
                }
                catch (Exception e)
                {
                    Send(client, "NG", e.Message.ToString());
                    MessageBox.Show(e.ToString());
                }
            }

            public static void Send(Socket client, String data, String ErrorMessage)
            {
                byte[] Status = Encoding.ASCII.GetBytes(data);
                byte[] errorMessage = Encoding.ASCII.GetBytes(ErrorMessage);
                byte[] statusSize = new byte[240];

                int i = new int();
                foreach (var ST in Status)
                {
                    i++;
                    if (i == 1)
                        statusSize[0] = ST;
                    if (i == 2)
                        statusSize[1] = ST;
                }
                if (data.Equals("NG"))
                {
                    int j = 2;
                    foreach (byte em in errorMessage)
                    {
                        statusSize[j] = em;
                        j++;
                    }
                }

                client.BeginSend(statusSize, 0, statusSize.Length, 0,
                    new AsyncCallback(SendCallback), client);
            }

            public static void SendCallback(IAsyncResult ar)
            {
                try
                {
                    Socket client = (Socket)ar.AsyncState;

                    int bytesSent = client.EndSend(ar);
                    MessageBox.Show(string.Concat("Sent bytes to server.", bytesSent.ToString()));
                    //SocketConnected(client);
                    sendDone.Set();
                    //MessageBox.Show("Send Callback");

                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            }
            public static bool SocketConnected(Socket s)
            {
                bool part1 = s.Poll(1000, SelectMode.SelectRead);
                bool part2 = (s.Available == 0);
                if (part1 && part2)
                    return false;
                else
                    return true;
            }

        }

        private void btnConnect_Click(object sender, EventArgs e)
        {

            AsynchronousClient.StartClient();
        }

        }

    }
}


You problem is, that for receiving, the other side is determing how much and when it will send data. You should create some sort of request message, but you must do continues receives.

  • So send the server a request for data on a interval.
  • Continues receiving.