从C#.net中的服务器连续读取数据

时间:2018-03-19 07:28:29

标签: c# .net server client listener

我的系统与某个服务器连接。我正在从服务器上读取数据。 但我想从服务器不断读取数据。 这是我的代码:

TcpClient client = new TcpClient("169.254.74.65", 7998);
NetworkStream stream = client.GetStream();
Byte[] data = new Byte[1024];
String responseData = String.Empty;
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
stream.Close();
client.Close();

有人能告诉我在哪里放置while循环以便能够连续收听?

2 个答案:

答案 0 :(得分:0)

要持续接收数据,您实际上需要进行一些循环。

例如:

 private void StartProcessing(Socket serverSocket)
{
    var clientSocket = serverSocket.Accept();
    StartReceiveing(clientSocket);
}

private void StartReceiveing(Socket clientSocket)
{
    const int maxBufferSize = 1024;

    try
    {
        while (true)
        {
            var buffer = new byte[maxBufferSize];

            var bytesRead = clientSocket.Receive(buffer);

            if (ClientIsConnected(clientSocket))
            {
                var actualData = new byte[bytesRead];

                Array.Copy(buffer, actualData, bytesRead);
                OnDataReceived(actualData);
            }
            else
            {
                OnDisconnected(clientSocket);
            }
        }
    }
    catch (SocketException ex)
    {
        Console.WriteLine(ex.Message);
    }
}

private void OnDisconnected(Socket issuedSocket)
{
    if (issuedSocket != null)
    {
        issuedSocket.Shutdown(SocketShutdown.Both);
        issuedSocket.Close();

        StartProcessing(listener);
    }
}

private void OnDataReceived(byte[] data)
{
    //do cool things
}

private static bool ClientIsConnected(Socket socket)
{
    return !(socket.Poll(1000, SelectMode.SelectRead) && socket.Available == 0);
}

答案 1 :(得分:0)

只需在不更改代码的情况下添加循环:

TcpClient client = new TcpClient("169.254.74.65", 7998);
NetworkStream stream = client.GetStream();
Byte[] data = new Byte[1024];
String responseData = String.Empty;
Int32 bytes;
while(true) {
    bytes = stream.Read(data, 0, data.Length);
    if (bytes > 0) {
        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
        Console.WriteLine("Received: {0}", responseData);
    }
}
stream.Close();
client.Close();

这样它将无限地从主线程中的服务器请求数据。 其他改进可能是:

  • 更改循环条件以指示您何时停止阅读;
  • 在没有可用数据时添加睡眠以避免浪费处理器时间;
  • 添加错误处理;
  • 使用异步方法重写代码。