每当有新数据时,TcpClient都不会读取

时间:2016-03-30 16:18:26

标签: c# sockets tcp tcpclient

我正在尝试创建一个程序,通过TCP Socket监听我的服务器,以便通知它。例如,如果我更新项目的价格,则连接到TCP服务器的所有客户端都会收到一个JSON字符串,告诉他们。我的想法是我的C#程序在整个运行时维护这个TCP套接字,只要有新数据就从套接字读取。

我的问题是TcpClient拒绝读取发送的第一轮字节。它读取,然后完全停止工作。代码如下:

TcpClient _client;
static int readBytesLength = 1024;
Byte[] readBytes = new byte[readBytesLength];

private void initClientConnection() {
    _client = new TcpClient();
    _client.BeginConnect(SERVER_IP, SERVER_PORT, new AsyncCallback(connectCallback), _client);
}

private void connectCallback(IAsyncResult result) {
    if (_client.Connected) {
        Console.WriteLine("Connected!");
        this.beginReading();
    }
    else {
        Console.WriteLine("Failed to connect, trying again!");
        this.initClientConnection();
    }
}


private void beginReading() {
    readBytes = new byte[readBytesLength];
    _client.GetStream().BeginRead(readBytes, 0, readBytesLength, receiveCallback, _client.GetStream());
}

private void receiveCallback(IAsyncResult result) {
    Console.WriteLine("Read Callback!");
    if (_client.GetStream().CanRead) {
        string response = Encoding.UTF8.GetString(readBytes);
        Console.WriteLine("Stream got \n{0}", response);
    }
    this.beginReading();
}

同样,我只收到1个批量数据而且它只是停止接收。

Stream got 
-----Received-----
{"status":"SUCCESS","message": "Log in confirmed (2)"}

1 个答案:

答案 0 :(得分:1)

您的代码中仍然存在一些奇怪的事情。没有理由使用Stream.CanRead您正在使用它的地方,并且您没有使用Encoding.GetString的正确重载。我已经清理了你的例子并修复了一些奇怪/不必要的位。

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class TcpConnection
{
    private const int BUF_SIZE = 1024;
    private readonly byte[] buffer = new byte[BUF_SIZE];
    private readonly TcpClient client = new TcpClient();

    public void Start(IPAddress ip, int port)
    {
        client.BeginConnect(ip, port, ConnectCallback, null);
    }

    private void ConnectCallback(IAsyncResult result)
    {
        client.EndConnect(result);
        Console.WriteLine("Connected!");
    }

    private void StartRead()
    {
        if(!client.Connected)
        {
            Console.WriteLine("Disconnected, can't read.");
            return;
        }
        NetworkStream stream = client.GetStream();
        stream.BeginRead(buffer, 0, BUF_SIZE, ReadCallback, stream);        
    }

    private void ReadCallback(IAsyncResult result)
    {
        NetworkStream stream = (NetworkStream)result.AsyncState;
        int bytesRead = stream.EndRead(result);
        Console.WriteLine("Read Callback!");
        if (bytesRead > 0)
        {
            string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Stream got \n{0}", response);
        }
        StartRead();
    }
}