c语言网络编程:C#网络编程(接收文件) -
Part.5
疯狂代码 / ĵ http://DotNet/Article65322.html
本文源代码下载地址
/2009_03/Network-Part5.rar
这篇文章将完成Part.4中剩余部分它们本来是篇完整文章但是上篇比较长合并起来页数太多浏览起来可能
会比较不方便我就将它拆为两篇了本文便是它后半部分我们继续进行上篇没有完成步骤:客户端接收来自服务端
文件
4.客户端接收文件
4.1服务端实现
对于服务端我们只需要实现上章遗留sendFile思路方法就可以了它起初在handleProtocol中是注释掉另外
由于创建连接、获取流等操作和receiveFile是没有区别所以我们将它提出来作为个公共思路方法
getStreamToClient下面是服务端代码只包含新增改过代码对于原有思路方法我只给出了签名
Server {
void Main( args) {
Console.WriteLine("Server is running ... ");
IPAddress ip = IPAddress.Parse("");
TcpListener listener = TcpListener(ip, 8500);
listener.Start; // 开启对控制端口 8500 侦听
Console.WriteLine("Start Listening ...");
while (true) {
// 获取个连接同步思路方法在此处中断
TcpClient client = listener.AcceptTcpClient;
RemoteClient wapper = RemoteClient(client);
wapper.BeginRead;
}
}
}
public RemoteClient {
// 字段 略
public RemoteClient(TcpClient client) {}
// 开始进行读取
public void BeginRead { }
// 再读取完成时进行回调
private void _disibledevent=> ProtocolHelper helper = ProtocolHelper(pro);
FileProtocol protocol = helper.GetProtocol;
(protocol.Mode FileRequestMode.Send) {
// 客户端发送文件对服务端来说则是接收文件
receiveFile(protocol);
} (protocol.Mode FileRequestMode.Receive) {
// 客户端接收文件对服务端来说则是发送文件
sendFile(protocol);
}
}
// 发送文件
private void sendFile(FileProtocol protocol) {
TcpClient localClient;
NetworkStream streamToClient = getStreamToClient(protocol, out localClient);
// 获得文件路径
filePath = Environment.CurrentDirectory + "/" + protocol.FileName;
// 创建文件流
FileStream fs = FileStream(filePath, FileMode.Open, FileAccess.Read);