使用C#进行点对点通讯和文件传输第1页使用C#进行点对点通讯和文件传输程序分三部分,包括发送部分、接受部分和一个两者共享的通讯基类,这个基类才是俺心血的结晶:)一、通讯基类usingSystem;usingSystem.Net.Sockets;usingSystem.Net;usingSystem.IO;usingSystem.Windows.Forms;usingSystem.Text;namespaceBaseClass{///传送信息的格式为给定长度的命令部分+给定长度的命令注释部分+可变长度的长度信息+可变长度的信息部分publicclassCommunClass{publicCommunClass(){//TODO:在此处添加构造函数逻辑}///命令部分的长度privatestaticreadonlyintCMDLEN=50;///命令注释部分的长度privatestaticreadonlyintDESCLEN=100;///可变长度的长度信息部分所占的字节数privatestaticreadonlyintDYNAMICLENGTHLEN=10;///每次处理可变信息部分的长度privatestaticreadonlyintDEALLEN=1024;////应答的最大长度privatestaticreadonlyintRESPONLEN=20;///用于填充命令或注释不足长度部分的字符privatestaticreadonlycharFILLCHAR=''^'';///成功发送一部分数据后的回调方法(也可以认为是触发的事件,但严格来说还不是)publicdelegatevoidOnSend(intiTotal,intiSending);///根据给定的服务器和端口号建立连接///服务器名///端口号publicstaticSocketConnectToServer(stringstrHost,intiPort){try{IPAddressipAddress=Dns.Resolve(strHost).AddressList[0];IPEndPointipPoint=newIPEndPoint(ipAddress,iPort);Sockets=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);使用C#进行点对点通讯和文件传输第2页s.Connect(ipPoint);returns;}catch(Exceptione){throw(newException(建立到服务器的连接出错+e.Message));}}///将文本写到Socket中///要发送信息的Socket///要发送的信息///是否成功publicstaticboolWriteTextToSocket(Sockets,stringstrInfo){byte[]buf=Encoding.UTF8.GetBytes(strInfo);try{s.Send(buf,0,buf.Length,SocketFlags.None);returntrue;}catch(Exceptionerr){MessageBox.Show(发送文本失败!+err.Message);returnfalse;}}///将命令文本写到Socket中///要发送命令文本的Socket///要发送的命令文本//是否成功publicstaticboolWriteCommandToSocket(Sockets,stringstrCmd){if(strCmd==)strCmd=NOP;strCmd=strCmd.PadRight(CMDLEN,FILLCHAR);returnWriteTextToSocket(s,strCmd);}//////将命令注释写到Socket中//////要发送命令注释的Socket///要发送的命令注释///是否成功publicstaticboolWriteCommandDescToSocket(Sockets,stringstrDesc){if(strDesc==)strDesc=0;strDesc=strDesc.PadRight(DESCLEN,FILLCHAR);returnWriteTextToSocket(s,strDesc);}///发送可变信息的字节数///要发送字节数的Socket///字节数///是否成功使用C#进行点对点通讯和文件传输第3页publicstaticboolWriteDynamicLenToSocket(Sockets,intiLen){stringstrLen=iLen.ToString().PadRight(DYNAMICLENGTHLEN,FILLCHAR);returnWriteTextToSocket(s,strLen);}///将缓存的指定部分发送到Socket///要发送缓存的Socket///要发送的缓存///要发送缓存的起始位置///要发送缓存的字节数///每次发送的字节说///每次发送成功后的回调函数///是否发送成功publicstaticboolWriteBufToSocket(Sockets,byte[]buf,intiStart,intiCount,intiBlock,OnSendSendSuccess){intiSended=0;intiSending=0;while(iSended{if(iSended+iBlockiSending=iBlock;elseiSending=iCount-iSended;s.Send(buf,iStart+iSended,iSending,SocketFlags.None);iSended+=iSending;if(ReadResponsionFromSocket(s)==OK)if(SendSuccess!=null)SendSuccess(iCount,iSended);elsereturnfalse;}returntrue;}///将长度不固定文本发送到socket///要发送文本的Socket///要发送的文本///成功发送一部分文本后的回调函数///得到文本长度的回调函数publicstaticboolWriteDynamicTextToSocket(Sockets,stringstrText,OnSendOnSendText){byte[]buf=Encoding.UTF8.GetBytes(strText);intiLen=buf.Length;try{使用C#进行点对点通讯和文件传输第4页WriteDynamicLenToSocket(s,iLen);returnWriteBufToSocket(s,buf,0,iLen,DEALLEN,OnSendText);}catch(Exceptionerr){MessageBox.Show(发送文本失败!+err.Message);returnfalse;}}///将文件写到Socket///要发送文件的Socket///要发送的文件///是否成功publicstaticboolWriteFileToSocket(Sockets,stringstrFile,OnSendOnSendFile){FileStreamfs=newFileStream(strFile,FileMode.Open,FileAccess.Read,FileShare.Read);intiLen=(int)fs.Length;WriteDynamicLenToSocket(s,iLen);byte[]buf=newbyte[iLen];try{fs.Read(buf,0,iLen);returnWriteBufToSocket(s,buf,0,iLen,DEALLEN,OnSendFile);}catch(Exceptionerr){MessageBox.Show(发送文件失败!+err.Message);returnfalse;}finally{fs.Close();}}///对方对自己消息的简单回应publicstaticstringReadResponsionFromSocket(Sockets){byte[]bufCmd=newbyte[RESPONLEN];intiCount=s.Receive(bufCmd);stringstrRespon=Encoding.UTF8.GetString(bufCmd,0,iCount);returnstrRespon;}///从Socket读取命令///要读取命令的Socket///读取的命令publicstaticstringReadCommandFromSocket(Sockets){使用C#进行点对点通讯和文件传输第5页byte[]bufCmd=newbyte[CMDLEN];intiCount=s.Receive(bufCmd,0,CMDLEN,SocketFlags.Partial);stringstrCommand=Encoding.UTF8.GetString(bufCmd,0,CMDLEN);returnstrCommand=strCommand.TrimEnd(FILLCHAR);}///读取命令注释///要读取命令注释的Socket///读取的命令注释publicstaticstringReadCommandDescFromSocket(Sockets){byte[]bufCmd=newbyte[DESCLEN];intiCount=s.Receive(bufCmd,0,DESCLEN,SocketFlags.Partial);stringstrCommand=Encoding.UTF8.GetString(bufCmd,0,DESCLEN);returnstrCommand=strCommand.TrimEnd(FILLCHAR);}///读取可变部分的长度//要读取可变部分长度的Socket///读取的可变部分的长度publicstaticintReadDynamicLenFromSocket(Sockets){byte[]bufCmd=newbyte[DYNAMICLENGTHLEN];intiCount=s.Receive(bufCmd,0,DYNAMICLENGTHLEN,SocketFlags.Partial);stringstrCommand=Encoding.UTF8.GetString(bufCmd,0,DYNAMICLENGTHLEN);returnint.Parse(strCommand.TrimEnd(FILLCHAR));}///读取文本形式的可变信息///要读取可变信息的Socket///读取的可变信息publicstaticstringReadDynamicTextFromSocket(Sockets){intiLen=ReadDynamicLenFromSocket(s);byte[]buf=newbyte[iLen];stringstrInfo=;intiReceiveded=0;intiReceiveing=0;while(iReceiveded{if(iReceiveded+DEALLENiReceiveing=DEALLEN;elseiReceiveing=iLen-iReceiveded;s.Receive(buf,iReceiveded,iReceiveing,SocketFlags.None);CommunClass.WriteTextToSocket(s,OK);iReceiveded+=iReceiveing;使用C#进行点对点通讯和文件传输第6页}strInfo=Encoding.UTF8.GetString(buf,0,iLen);returnstrInfo;}//////读取文件形式的可变信息//////要读