/// <summary>
/// 向客户端异步发送文件
/// </summary>
/// <param name="ip"></param>
/// <param name="port"></param>
/// <param name="filePath"></param>
public async Task SendToClientFileAsync(string ip, int port, string filePath, Message msg)
{
// 新建 Udp 用于发送文件
var sendClient = new UdpClient();
try
{
FileInfo fileInfo = new FileInfo(filePath);
msg.Type = MessageEnum.FILE; // 设置发送文件标识
msg.FileLength = fileInfo.Length;
msg.FileName = Regex.Match(filePath, @"\\([^\\]+\.[^\\]+)").Groups[1].Value; // 获取文件名
byte[] datagram = Encoding.Unicode.GetBytes(JsonConvert.SerializeObject(msg));
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
/*
* 向‘原’远程客户端发送请求传送文件的请求,
* 接收‘新’远程客户端的响应,获取传送文件的端口
*
* 注:原远程客户端用于发送消息,新远程客户端用于发送文件
*/
await sendClient.SendAsync(datagram, datagram.Length, endPoint);
//IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
UdpReceiveResult result = await sendClient.ReceiveAsync().ConfigureAwait(false); // 阻塞直到接收到远程客户端的响应
/*
* 开始发送文件
*/
byte[] buffer = new byte[MAXSIZE];
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 1, true))
{
int percent = 0;
int count = 0;
while ((count = await fs.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
{
//await Task.Delay(10);
await sendClient.SendAsync(buffer, count, result.RemoteEndPoint);
if (Client.SendFileProgressNotify != null)
{
Client.SendFileProgressNotify(String.Format("{0:F2}%", (percent += count) / msg.FileLength * 100));
}
}
sendClient.Close();
}
}
catch (Exception e)
{
Log.Write(e.Message);
}
}