udp文件传输的问题,求高手解答
我写了一个程序,运行起来发现不对,请高手赐教发送端
private void StartSend()
{
int PacketSize = int.Parse(this.textBox6.Text);
//数据包
byte[] data = new byte[PacketSize];
//创建一个文件对象
FileInfo EzoneFile = new FileInfo(this.textBox1.Text);
//打开文件流
FileStream EzoneStream = EzoneFile.OpenRead();
//包的大小
//包的数量
int PacketCount = (int)(EzoneStream.Length / ((long)PacketSize));
this.textBox8.Text = PacketCount.ToString();
this.progressBar1.Maximum = PacketCount;
//最后一个包的大小
int LastDataPacket = (int)(EzoneStream.Length - ((long)(PacketSize * PacketCount)));
this.textBox9.Text = LastDataPacket.ToString();
//创建一个网络端点
EndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1") , int.Parse(this.textBox5.Text));
//创建一个套接字
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//开始循环发送数据包
for (int i = 0; i < PacketCount; i++)
{
//从文件流读取数据并填充数据包
EzoneStream.Read(data, 0, data.Length);
server.SendTo(data, ipep);
//显示发送数据包的个数
this.textBox10.Text = ((int)(i + 1)).ToString();
//进度条值的显示
this.progressBar1.PerformStep();
}
//如果还有多余的数据包,则应该发送完毕!
if (LastDataPacket != 0)
{
data = new byte[LastDataPacket];
EzoneStream.Read(data, 0, data.Length);
server.SendTo(data, ipep);
this.progressBar1.Value = this.progressBar1.Maximum;
}
//关闭套接字
server.Close();
//关闭文件流
EzoneStream.Close();
this.button2.Enabled = true;
MessageBox.Show("文件传输完毕!");
}
接收端
private void StartReceive()
{
int SendedCount = 0;
int total = 0;
int recv;
byte[] datasize = new byte[4]; //用于接收文件大小
byte[] receiveBytes = new byte[0]; //用于接收文件名
//指向远程服务端节点
EndPoint ipep = new IPEndPoint(IPAddress.Parse(this.textBox1.Text), int.Parse(this.textBox5.Text));
IPEndPoint ipep1 = new IPEndPoint(IPAddress.Parse(this.textBox1.Text), int.Parse(this.textBox5.Text));
//创建套接字
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
UdpClient uu = new UdpClient(int.Parse(this.textBox5.Text));
client.Bind(ipep1);
receiveBytes = uu.Receive(ref ipep1);
//获得[文件名]
string SendFileName = System.Text.Encoding.Unicode.GetString(receiveBytes);
//创建一个新文件
FileStream MyFileStream = new FileStream(SendFileName, FileMode.Create, FileAccess.Write);
//已发送包的个数
recv = client.ReceiveFrom(datasize,ref ipep);
int size = BitConverter.ToInt32(datasize, 0);
int dataleft = size;
byte[] data1 = new byte[size];//用于接收文件
while (total < size)
{
recv = client.ReceiveFrom(data1,ref ipep);
if (recv == 0)
{
data1 = null;
break;
}
total += recv;
dataleft -= recv;
}
while (true)
{
byte[] data = data1;
if (data.Length == 0)
{
break;
}
else
{
SendedCount++;
//将接收到的数据包写入到文件流对象
MyFileStream.Write(data, 0, data.Length);
}
}
//关闭文件流
MyFileStream.Close();
//关闭套接字
client.Close();
this.button1.Enabled = true;
MessageBox.Show("文件接收完毕!");
}