日期:2014-05-20 浏览次数:20869 次
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace CaijiTest
{
class NetReceiveBuffer
{
TcpClient tc;
int BufferLength;
byte[] NetBuffer;
NetworkStream netStream;
Thread thread;
ThreadStart ts;
int iPosition=0;
byte bt;
public NetReceiveBuffer(string ip,int port,int length)
{
BufferLength = length;
NetBuffer = new byte[length];
tc = new TcpClient(ip, port);
netStream = tc.GetStream();
ts = new ThreadStart(Receive);
thread = new Thread(ts);
thread.Start();
}
public int BytesToRead
{
get
{
return iPosition;
}
}
private void Receive()
{
while (true)
{
Thread.Sleep(1);
NetBuffer[iPosition] = (byte)netStream.ReadByte();
iPosition++;
if (iPosition == NetBuffer.Length)
{
Buffer.BlockCopy(NetBuffer, 1, NetBuffer, 0, NetBuffer.Length - 1);//丢弃第一个字节,后续数据向前移动一个字节
iPosition--;//回到缓冲区最后一个字节的位置
}
}
}
public void Read(byte[] buffer, int offset, int size)
{
lock (this)
{
Buffer.BlockCopy(NetBuffer, 0, buffer, offset, size);
Buffer.BlockCopy(NetBuffer, size, NetBuffer, 0, iPosition - size);
iPosition -= size;
}
}
public byte ReadByte()
{
lock (this)
{
bt = NetBuffer[0];
Buffer.BlockCopy(NetBuffer, 1, NetBuffer, 0, iPosition - 1);//丢弃第一个字节,后续数据向前移动一个字节