以指定的时间间隔从tcp服务器连续读取数据

时间:2016-11-04 11:53:46

标签: c# sockets tcpclient windows-applications

我需要实现tcp socket Client。我们必须从服务器tcp套接字接收具有特定时间间隔的数据。如果我们从客户端发出连接请求,那么连接将不会断开连接。我们必须在服务器发送数据时接收数据。我已经尝试过异步客户端通信来自MSDN网站。但接收回调函数在接收方法中被调用。所以我们必须从服务器接收数据而没有任何间隔。如果没有连续接收数据,则连接将完成接收并且连接断开连接。

任何人都可以帮助我...谢谢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();
        }



        }

    }
}

2 个答案:

答案 0 :(得分:0)

在新线程中创建套接字客户端,然后开始永久阅读。

using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;

namespace TCPClient
{
class TCPClient
{

    [STAThread]
    static void Main(string[] args)
    {
        TCPClient client = null;
        client = new TCPClient("filename");

    }

    private String m_fileName=null;
    public TCPClient(String fileName)
    {
        m_fileName=fileName;
        Thread t = new Thread(new ThreadStart(ClientThreadStart));
        t.Start();
    }

    private void ClientThreadStart()
    {
        Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
        clientSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"),31001));

        // Send some data if erquired.
        clientSocket.Send(Encoding.ASCII.GetBytes("testdata"));

        // Receive the data whenver available.
        while(1)
        {
        byte [] data = new byte[1024];
        clientSocket.Receive(data);
        int length=BitConverter.ToInt32(data,0);

    //check if  you have received all the data and sleep for time interval. with Sleep(timeInterval), Do only after you have received all available data for instance.
        }

        clientSocket.Close();
    }

}

}

答案 1 :(得分:0)

你的问题是,对于接收,另一方正在确定它将发送数据的次数和时间。您应该创建某种请求消息,但您必须继续接收。

  • 因此,请在一段时间内向服务器发送数据请求。
  • 继续接收。