17,741
社区成员
发帖
与我相关
我的任务
分享
private void ReceiveByte(byte[] receiveByte)
{
IAsyncResult iar = ns.BeginRead(receiveByte, 0, receiveByte.Length, null, null);
int count = sleepCount;
if (!iar.IsCompleted)
{
if (count <= 0)
{
receiveByte = null;
return;
}
Thread.Sleep(sleepMilliseconds);
count--;
}
try
{
ns.EndRead(iar);
return;
}
catch (Exception)
{
receiveByte = null;
return;
}
public bool Send(byte[] sendByte,int offset,int size )
{
IAsyncResult iar = ns.BeginWrite(sendByte, offset,size, null, null);
int count = sleepCount;
if (!iar.IsCompleted)
{
if (count <= 0)
{
return false;
}
Thread.Sleep(sleepMilliseconds);
count--;
}
try
{
ns.EndWrite(iar);
ns.Flush();
return true;
}
catch (Exception)
{
return false;
}
}
public bool SendFile(string path, int bufferSize)
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
int count = sleepCount; //循环次数
int readCount = 0; //当前读到的文件流字节数
byte[] sendBufs = new byte[bufferSize]; //发送缓存
int fileLength = (int)fs.Length;
string fileName = Path.GetFileName(path);
byte[] packetFirst = Joinhead4(string.Format("|{0}|{1}|", fileName, fileLength.ToString()));
if (!pt.Send(packetFirst)) //发送头包
return false;
#region 关键代码
while ((readCount = fs.Read(sendBufs,0,sendBufs.Length)) != 0)
{//以缓存大小分片循环发送文件内容
if (!pt.Send(sendBufs,0,readCount))
{
return false;
}
}
fs.Close();
#endregion
return true;
}
public void ReceiveFile(string directoryPath,int bufferSize)
{
//先接收头包 以得到文件名和文件长度
byte [] packetFirst = pt.ReceiveOnePacket(4);//根据4字节包头指定长度接收头包
string rec = DropHead4(packetFirst);//去掉包头得到头包字符串信息
rec = rec.Remove(0, 1);//去掉最前的分隔线
rec = rec.Remove(rec.Length - 1, 1);//去掉最后的分隔线
string[] fileds = rec.Split(new string[] { "|" }, StringSplitOptions.None);//得到数据字段
string fileName = fileds[0];
string fileFullPath = directoryPath + fileds[0];
int fileLength = int.Parse(fileds[1]);
FileStream fs = new FileStream(fileFullPath, FileMode.Create, FileAccess.ReadWrite);
//循环接收文件内容
int receiveLength = fileLength; //需要接收的文件总字节数
byte[] recBufs = new byte[bufferSize]; //接收缓存
while (receiveLength > 0)
{
recBufs = pt.ReceiveLength(recBufs.Length);
if (receiveLength > recBufs.Length)
{
fs.Write(recBufs, 0, recBufs.Length);
}
else
{
fs.Write(recBufs, 0, receiveLength);
}
fs.Flush();
receiveLength -= recBufs.Length;
}
//wr.Close();
fs.Close();
}