public void SendFile(string filePath) { IPAddress ip = IPAddress.Parse("127.0.0.1"); TcpListener listener = new TcpListener(ip, 0); listener.Start(); // 获取本地监听的端口号 IPEndPoint endPoint = listener.LocalEndpoint as IPEndPoint; int listeningPort = endPoint.Port; // 获取发送的协议字符串 string fileName = Path.Combine(filePath); FileProtocol protocol = new FileProtocol(FileRequestMode.Send, listeningPort, fileName); string pro = protocol.ToString(); // 发送协议到服务器 SendMessage(pro); // 中断,等待远程连接 TcpClient localClient = listener.AcceptTcpClient(); Console.WriteLine("Start sending file……"); NetworkStream stream = localClient.GetStream(); // 创建文件流 FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); byte[] fileBuffer = new byte[1024]; //每次传递1kb int bytesRead = 0; int totalBytes = 0; // 创建获取文件发送状态的类 SendStatus status = new SendStatus(filePath); // 将文件流写入网络流 try { do { Thread.Sleep(TimeSpan.FromMilliseconds(10)); // 模拟网络传输延迟 bytesRead = fs.Read(fileBuffer, 0, fileBuffer.Length); stream.Write(fileBuffer, 0, bytesRead); totalBytes += bytesRead; status.PrintStatus(totalBytes); } while (bytesRead > 0); } catch (Exception e) { Console.WriteLine(e.Message); } finally { stream.Dispose(); fs.Dispose(); localClient.Close(); listener.Stop(); } }
// 发送文件 -- 同步方法 public void SendFile(string filePath) { IPAddress ip = IPAddress.Parse("127.0.0.1"); TcpListener listener = new TcpListener(ip, 0); listener.Start(); // 获取本地侦听的端口号 IPEndPoint endPoint = listener.LocalEndpoint as IPEndPoint; int listeningPort = endPoint.Port; // 获取发送的协议字符串 string fileName = Path.GetFileName(filePath); FileProtocol protocol = new FileProtocol(FileRequestMode.Send, listeningPort, fileName); string pro = protocol.ToString(); SendMessage(pro); // 发送协议到服务端 // 中断,等待远程连接 TcpClient localClient = listener.AcceptTcpClient(); Console.WriteLine("Start sending file..."); NetworkStream stream = localClient.GetStream(); // 创建文件流 FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); byte[] fileBuffer = new byte[1024]; // 每次传1KB int bytesRead; int totalBytes = 0; // 创建获取文件发送状态的类 SendStatus status = new SendStatus(filePath); // 将文件流转写入网络流 try { do { Thread.Sleep(10); // 为了更好的视觉效果,暂停10毫秒:-) bytesRead = fs.Read(fileBuffer, 0, fileBuffer.Length); stream.Write(fileBuffer, 0, bytesRead); totalBytes += bytesRead; // 发送了的字节数 status.PrintStatus(totalBytes); // 打印发送状态 } while (bytesRead > 0); Console.WriteLine("Total {0} bytes sent, Done!", totalBytes); } catch { Console.WriteLine("Server has lost..."); } stream.Dispose(); fs.Dispose(); localClient.Close(); listener.Stop(); }