我用tcpclient获取服务端发送的数据,代码如下:
private void Read(StringBuilder sb)
{
List<byte> bytesList = new List<byte>();
NetworkStream ns = tcpCli.GetStream();
while (tcpCli.Available > 0)
{
int input = ns.ReadByte();
//将byte加入List中
bytesList.Add((byte)input);
}
byte[] bytes = new byte[bytesList.Count];
bytesList.CopyTo(bytes);
sb.Append(textEncoder.GetString(bytes));
}
但是经过测试,我发现tcpCli.Available 不可靠,在某一时刻tcpCli.Available<0,程序跳出循环,
但实际上还有很多数据Available的。该问题如何解决,大虾们请指教。在线等
private void Read(StringBuilder sb)
{
List<byte> bytesList = new List<byte>();
NetworkStream ns = tcpCli.GetStream();
while (tcpCli.Available > 0)
{
int input = ns.ReadByte();
//将byte加入List中
bytesList.Add((byte)input);
}
byte[] bytes = new byte[bytesList.Count];
bytesList.CopyTo(bytes);
sb.Append(textEncoder.GetString(bytes));
}
但是经过测试,我发现tcpCli.Available 不可靠,在某一时刻tcpCli.Available<0,程序跳出循环,
但实际上还有很多数据Available的。该问题如何解决,大虾们请指教。在线等
if(myNetworkStream.CanRead){
byte[] myReadBuffer = new byte[1024];
StringBuilder myCompleteMessage = new StringBuilder();
int numberOfBytesRead = 0; // Incoming message may be larger than the buffer size.
do{
numberOfBytesRead = myNetworkStream.Read(myReadBuffer, 0, myReadBuffer.Length); myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
}
while(myNetworkStream.DataAvailable); // Print out the received message to the console.
Console.WriteLine("You received the following message : " +
myCompleteMessage);
}
else{
Console.WriteLine("Sorry. You cannot read from this NetworkStream.");
}
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
{
stream.BeginRead(buffer, 0, BufferSize, new AsyncCallback(ReadCallback), stream);
} public void ReadCallback(IAsyncResult ar)
{ // Retrieve the state object and the handler socket
// from the asynchronous state object.
NetworkStream stream= (NetworkStream)ar.AsyncState;
int bytesRead;
// Read data from the tcpclient.
bytesRead = stream.EndRead(ar);
Console.WriteLine(bytesRead);
if (bytesRead > 0)
{
Array.Copy(bytes, buffer, bytesRead );
sb.Append(textEncoder.GetString(bytes));
stream.BeginRead(buffer, 0, BufferSize, new AsyncCallback(ReadCallback), stream);
}
}
谢谢你的回答,但是你的解答还是不能解决我的问题。
我是这样一个情况:
服务端发送大量的数据,数据的大小大于接收端缓冲区的大小,因此我在接收的时候用
TcpClient.Avaliable来判断数据是否已经接收完成,但是该属性却是不可靠的。有时候Avaliable<=0,但是实际上还有数据。改用异步接收的方式,在回调函数里还是会用到DataAvaliable在这个不可靠的属性。
public class StateObject
{
public NetworkStream ns = null;
public int BufferSize = 256;
public byte[] buffer = new byte[256];
public List<byte> byteList = null;
}
//回调函数
private void ReadCallBack(IAsyncResult ar)
{
StateObject stateObject = (StateObject)ar.AsyncState;
NetWorkStream ns = stateObject.ns;
if (ns.DataAvaliable> 0)
{
stateObject.byteList.Add((byte)ns.ReadByte());
}
}