using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace 文件传输
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iped = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10000);
int orze = 0;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string ip,port,str;
socket.Bind(iped); //与当前一个套接字进行绑定
EndPoint ep = (EndPoint)(new IPEndPoint(IPAddress.Any,0));
byte[] buff=new byte[1024];
socket.ReceiveFrom(buff, ref ep); //侦听传入请求
//sendfile = Encoding.Unicode.GetString(buff);
//sendfile = sendfile.Substring(0, Convert.ToInt32(sendfile.Substring(0, 3)));
str = ((IPEndPoint)ep).ToString();
ip = str.Substring(0, str.IndexOf(":"));
port = str.Substring(str.IndexOf(":") + 1); //记录IP地址
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip),Convert.ToInt32(port));
byte[] b = Encoding.Unicode.GetBytes("1");
socket.SendTo(b, ipe); //发送模拟的同意信号
Stream sr = new FileStream("f:\\test.rar", FileMode.Create, FileAccess.ReadWrite); //创建一个流
while (true)
{
socket.ReceiveFrom(buff, ref ep);//接收传入的数据
try
{
str = Encoding.Unicode.GetString(buff);
if (str.Substring(0, 6) == "TheEnd") //判断文件的传输是否结束
break;
}
catch
{}
sr.Write(buff,0,(int)(buff.Length)); //将接收到的数据写入流
socket.SendTo(b,ipe); //请求下一段数据
}
sr.Close(); //关闭当前流
MessageBox.Show("文件接收成功!");
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
Stream ss=new FileStream ("e:\\test.rar",FileMode.Open,FileAccess.ReadWrite);
//string mess = "sss";
byte[] buff=new byte[1024];
EndPoint ep=((EndPoint)iped);
socket.SendTo(Encoding.Unicode.GetBytes("1"), iped); //发送模拟的文件传输请求
socket.ReceiveFrom(buff, ref ep); //等待对方回应
do
{
buff = new byte[1024];
orze = ss.Read(buff, 0, 1024);
socket.SendTo(buff, iped);
socket.ReceiveFrom(buff, ref ep);
} while (orze > 0);
buff = Encoding.Unicode.GetBytes("TheEnd");
socket.SendTo(buff, iped); //发送结束信号
ss.Close(); //关闭文件流
MessageBox.Show("文件传送已完成!");
// orze = 0;
}
private void button2_Click(object sender, EventArgs e)
{
backgroundWorker2.RunWorkerAsync();
}
}
}