110,566
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 定义委托
/// </summary>
/// <param name="m_t">文件大小</param>
/// <param name="m_p">当前位置</param>
public delegate void SendFileHandler(int m_t, int m_p);
/// <summary>
/// 定义事件,这个事件将被主线程捕捉,并对主线程 进度条进行修改。
/// </summary>
public event SendFileHandler m_SpFlHandler;
public void SendFile()
{
m_SpFlHandler += new SendFileHandler(ChgProgress);
Thread t = new Thread(StartSend);
t.Start();
}
//开始发送文件
public void StartSend()
{
//连接到对方客服端
p2pClient= this.GetP2PClient();
ns=p2pClient.GetStream();
FileStream fs = new FileStream(fullName, FileMode.Open, FileAccess.Read);
this.progressBar1.Visible = true;
this.label10.Visible = true;
int m_totalSize = 0;
int m_curPosition = 0;
//源文件大小
m_totalSize = (int)fs.Length;
byte[] bys = new byte[length];
while (true)
{
int read=fs.Read(bys, 0, bys.Length);
if (read <= 0)
{
break;
}
ns.Write(bys, 0, bys.Length);
ns.Flush();
m_curPosition += read;
this.label10.Text = string.Format("{0}%", (int)(m_curPosition*100/m_totalSize));
//触发事件
m_SpFlHandler(m_totalSize, m_curPosition);
Thread.Sleep(50);
}
this.progressBar1.Visible = false;
this.richTextBox2.Text += string.Format("文件:{0} 发送成功,(总大小:{1}KB)\r\n", fileName, (int)length / 1024);
this.richTextBox2.SelectionStart = this.richTextBox2.Text.Length;
this.richTextBox2.ScrollToCaret();
}
//改变进度条的值
private void ChgProgress(int m_t, int m_p)
{
progressBar1.Maximum = m_t;
progressBar1.Value = m_p;
}
filestream=new FileStream(richTextBox2.Lines[j-2].ToString(),FileMode.Open,FileAccess.Read);
//定义缓冲区
byte[] bb=new byte[1024];
//循环读文件
while((number=filestream.Read(bb,0,1024))!=0)
{//向客户端发送流
//sock.Send(bb,bb.Length,0);
stream.Write(bb,0,1024);
//刷新流
stream.Flush();
bb=new byte[1024];
}
bb=new byte[1024];
bb=System.Text.Encoding.ASCII.GetBytes("<EOF>");
sock.Send(bb);
stream.Flush();
filestream.Close();
//sock.Close();
stream.Close();
private void down(ref NetworkStream stream)
{
int length=1024;
byte[] bye=new byte[1024];
int tt=stream.Read(bye,0,length);
//下行循环读取网络流并写进文件
while(tt>0)
{
string ss=System.Text.Encoding.ASCII.GetString(bye);
int x=ss.IndexOf("<EOF>");
if(x!=-1)
{
filestream.Write(bye,0,x);
filestream.Flush();
break;
}
else
{
filestream.Write(bye,0,tt);
filestream.Flush();
}
tt=stream.Read(bye,0,length);
}//对用于while(!control)的“{”
filestream.Close();
MessageBox.Show("下载完毕!");