点对点接收端函数: public void fileClient()
{
if(MessageBox.Show("是否接受文件"+receiveData+"来源于:"+ipAddress,"接收文件",MessageBoxButtons.OKCancel,MessageBoxIcon.Information)==DialogResult.OK)
{
string s=receiveData.Substring(receiveData.LastIndexOf("."));
SaveFileDialog saveFile=new SaveFileDialog();
saveFile.Filter="*"+s+"|"+"*"+s;
if(saveFile.ShowDialog()==DialogResult.OK)
{
string fileName=saveFile.FileName;
TcpClient client=new TcpClient();
client.Connect(IPAddress.Parse(ipAddress),this.filePort);
NetworkStream ns=client.GetStream();
FileInfo f=new FileInfo(fileName);
FileStream fs=new FileStream(fileName,FileMode.Create);
byte[] b=new byte[1024];
while(ns.Read(b,0,b.Length)!=0)
{
fs.Write(b,0,b.Length);
fs.Flush();
}
ns.Close();
fs.Close();
MessageBox.Show("文件传输完毕!","发送文件...",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}
else
{ //拒绝接受文件
CUserUI.SendMessage(2,Encoding.Default.GetBytes(""),ipAddress);
}
}发送端函数:
public void fileServer()
{
if(this.openFileDialog1.ShowDialog()==DialogResult.OK)
{
string fileName=this.openFileDialog1.FileName;
string fileTitle=fileName.Substring(fileName.LastIndexOf("\\")+1,fileName.Length-fileName.LastIndexOf("\\")-1);
richBoxChat.AppendText("等待对方接收文件"+": "+fileTitle+"请等待回应\n");
CUserUI.SendMessage(1,Encoding.Default.GetBytes(fileTitle),CUserUI.friendsInfo[this.index].IP); int filePort=5001;
TcpListener tcpListener=new TcpListener(filePort);
tcpListener.Start();
TcpClient client=tcpListener.AcceptTcpClient();
NetworkStream ns=client.GetStream();
FileInfo f=new FileInfo(fileName);
int index=0;
FileStream fs=new FileStream(fileName,FileMode.Open);
byte[] b=new byte[1024];
while(index<f.Length)
{
fs.Read(b,0,b.Length);
index+=b.Length;
ns.Write(b,0,b.Length);
}
fs.Flush();
ns.Close();
fs.Close();
this.richBoxChat.AppendText("文件传输完毕!");
}
}