服务的建立类似之前的文章:https://blog.youkuaiyun.com/glmushroom/article/details/84955240
文件服务的区别ServiceHost的typeof的类型:
UriBuilder uriBuilder = new UriBuilder(Uri.UriSchemeHttp, host, port, FilesService.strServiceName);
FilesService._host = new ServiceHost(typeof(FileService), new Uri[]
{
uriBuilder.Uri
});
客户端连接服务器后,利用RPC模式远程调用服务端上的UploadFile接口。
注意:客户端文件流的重写方法Read是在调用了RPC服务端方法时执行的
public bool UploadFile(string LocalFileFullPath, FileInfoRequest request)
{
bool result = false;
try
{
if (!request.ForderPath.EndsWith("\\"))
{
request.ForderPath += "\\";
}
FileInfo fileInfo = new FileInfo(LocalFileFullPath);
if (!fileInfo.Exists)
{
throw new FileNotFoundException("File not found", request.FileName);
}
using (FileStream fileStream = new FileStream(LocalFileFullPath, FileMode.Open, FileAccess.Read))
{
using (StreamWithUpLoadProgress streamWithUpLoadProgress = new StreamWithUpLoadProgress(request.FileID, fileStream))
{
streamWithUpLoadProgress.ProgressChanged += new EventHandler<StreamWithUpLoadProgress.ProgressChangedEventArgs>(this.uploadStreamWithProgress_ProgressChanged);
RemoteFileInfo request2 = new RemoteFileInfo
{
FileID = request.FileID,
FileName = request.FileName,
ForderPath = request.ForderPath,
Length = fileInfo.Length,
FileByteStream = streamWithUpLoadProgress
};
this._service.UploadFile(request2);
}
}
result = true;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
return result;
}
this._service.UploadFile(request2);调用时,通讯层调用远程的Upload方法:
public void UploadFile(RemoteFileInfo request)
{
try
{
if (!Directory.Exists(request.ForderPath))
{
Directory.CreateDirectory(request.ForderPath);
}
string path = Path.Combine(request.ForderPath, request.FileName);
if (File.Exists(path))
{
File.Delete(path);
}
int num = 2048;
byte[] buffer = new byte[num];
using (FileStream fileStream = new FileStream(path, FileMode.CreateNew, FileAccess.Write))
{
while (true)
{
int num2 = request.FileByteStream.Read(buffer, 0, num);
if (num2 == 0)
{
break;
}
fileStream.Write(buffer, 0, num2);
}
fileStream.Close();
}
}
catch (Exception ex)
{
throw ex;
}
}
调用过程是利用RPC框架实现的:
客户端调用远程方法UploadFile,通讯层调用了文件流的重写方法Read。