由于是单向请求,就是说主动的只有客户端。
当客户端上传文件的时候,需要先传给服务端一个数据,告诉服务端它将要上传文件以及文件的大小,客户端要求的分包大小,将要发送的分包个数,原路径,目标路径等等,服务端根据这个信息查找临时文件,看是否接受过此文件,如果接受过,服务端发送一条数据给客户端告诉客户端,已经接受到的文件大小,分包个数,分包大小,然后客户端调整分包大小,发送一条数据到服务端,告诉服务端它协议解析正确开始发送数据,服务端发送确认消息,客户端开始发送文件数据,服务端开始接受文件数据并将其写入文件,发送完成之后,客户端发数据告诉服务端发送完成,服务端核对文件信息,发送确认信息给客户端,关闭socket链接。
当客户端下载文件的时候,需要先传给服务端一个数据,告诉服务端它将要下载文件,客户端要求的分包大小,原路径,目标路径,已经接受的分包个数,分包大小等等,服务端根据这个信息查找文件,发送一条数据给客户端告诉客户端文件大小,分包个数,分包大小,然后客户端发送一条数据到服务端,告诉服务端它协议解析正确开始接受数据,服务端发送确认消息,服务端开始发送文件数据,客户端开始接受文件数据并将其写入文件,发送完成之后,服务端发数据告诉客户端发送完成,客户端核对文件信息,发送确认信息给服务端,关闭socket链接。
由于篇幅,只贴几个方法的代码
private void sendMsg(string srcPath, string dirPath, bool isUpdate, string fName, long fLength, long dLength, long dNumber)
{
string msg = srcPath + "*" + dirPath + "*" + isUpdate + "*" + fName + "*" + fLength + "*" + dLength + "*" + dNumber;
try
{
socket.Send(Encoding.UTF8.GetBytes(msg));
}
catch(Exception ex)
{
throw new Exception("Send message error:\n " + ex);
}
}
{
string msg = srcPath + "*" + dirPath + "*" + isUpdate + "*" + fName + "*" + fLength + "*" + dLength + "*" + dNumber;
try
{
socket.Send(Encoding.UTF8.GetBytes(msg));
}
catch(Exception ex)
{
throw new Exception("Send message error:\n " + ex);
}
}
private void reciveFile(string srcPath, string dirPath,string fName,long dLength,long dReciveNumber,long dNumber)
{
FileStream fs = null;
try
{
try
{
fs = new FileStream(dirPath, FileMode.OpenOrCreate);
string dir = "sendRes:OK:OK";
sendDir(dir);
}
catch (Exception ex)
{
string dire = "sendRes:error:" + ex.ToString();
sendDir(dire);
throw ex;
}
byte[] buffer = new byte[dLength];
while (true)
{
//Thread.Sleep(1);
int n = socket.Receive(buffer);
dReciveNumber++;
fs.Write(buffer, 0, n);
fs.Flush();
if (dReciveNumber==dNumber)
{
break;
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (fs != null)
{
fs.Close();
}
}
}
{
FileStream fs = null;
try
{
try
{
fs = new FileStream(dirPath, FileMode.OpenOrCreate);
string dir = "sendRes:OK:OK";
sendDir(dir);
}
catch (Exception ex)
{
string dire = "sendRes:error:" + ex.ToString();
sendDir(dire);
throw ex;
}
byte[] buffer = new byte[dLength];
while (true)
{
//Thread.Sleep(1);
int n = socket.Receive(buffer);
dReciveNumber++;
fs.Write(buffer, 0, n);
fs.Flush();
if (dReciveNumber==dNumber)
{
break;
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (fs != null)
{
fs.Close();
}
}
}
就到这儿吧