程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> 使用C#進行點對點通訊和文件傳輸(通訊基類部分)

使用C#進行點對點通訊和文件傳輸(通訊基類部分)

編輯:.NET實例教程

最近一個項目要用到點對點文件傳輸,俺就到處找資料寫程序,最後終於完成了,為了讓別人少走些彎路,俺決定將俺程序中最重要的部分貢獻出來,希望對大家有所幫助。



俺的程序分三部分,包括發送部分、接受部分和一個兩者共享的通訊基類,這個基類才是俺心血的結晶:)



一、通訊基類

using System;

using System.Net.Sockets;

using System.Net ;

using System.IO ;

using System.Windows.Forms;

using System.Text;



namespace BaseClass

{

/// <summary>

/// 傳送信息的格式為 給定長度的命令部分+給定長度的命令注釋部分+可變長度的長度信息+可變長度的信息部分

/// </summary>

public class CommunClass

{

public CommunClass()

{

//

// TODO: 在此處添加構造函數邏輯

//

}

/// <summary>

/// 命令部分的長度

/// </summary>

private static readonly int CMDLEN = 50 ;

/// <summary>

/// 命令注釋部分的長度

/// </summary>

private static readonly int DESCLEN = 100 ;

/// <summary>

/// 可變長度的長度信息部分所占的字節數

/// </summary>

private static readonly int DYNAMICLENGTHLEN = 10 ;

/// <summary>

/// 每次處理可變信息部分的長度

/// </summary>

private static readonly int DEALLEN = 1024 ;

/// <summary>

/// /應答的最大長度

/// </summary>

private static readonly int RESPONLEN = 20 ;

/// <summary>

/// 用於填充命令或注釋不足長度部分的字符

/// </summary>

private static readonly char FILLCHAR = '^' ;



/// <summary>

/// 成功發送一部分數據後的回調方法(也可以認為是觸發的事件,但嚴格來說還不是)

/// </summary>

public delegate void OnSend(int iTotal,int iSending) ;



/// <summary>

/// 根據給定的服務器和端口號建立連接

/// </summary>

/// <param name="strHost">服務器名</param>

/// <param name="iPort">端口號</param>

/// <returns></returns>

public static Socket ConnectToServer(string strHost,int iPort)

{

try

{

IPAddress ipAddress = Dns.Resolve(strHost).AddressList[0];

IPEndPoint ipPoint = new IPEndPoint(ipAddress,iPort) ;



Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp) ;

s.Connect(ipPoint) ;

return s ;

}

catch (Exception e)

{

throw (new Exception("建立到服務器的連接出錯" + e.Message)) ;

}

}

/// <summary>

/// 將文本寫到Socket中

/// </summary>

/// <param name="s">要發送信息的Socket</param>

/// <param name="strInfo">要發送的信息</param>

/// <returns>是否成功</returns>

public static bool WriteTextToSocket(Socket s,string strInfo)

{

byte [] buf = Encoding.UTF8.GetBytes(strInfo) ;

try

{

s.Send(buf,0,buf.Length,SocketFlags.None) ;

return true ;

}

catch(Exception err)

{

MessageBox.Show("發送文本失敗!"+err.Message) ;

return false ;

}

}

/// <summary>

/// 將命令文本寫到Socket中

/// </summary>

/// <param name="s">要發送命令文本的Socket</param>

/// <param name="strInfo">要發送的命令文本</param>


/// <returns>是否成功</returns>

public static bool WriteCommandToSocket(Socket s,string strCmd)

{

if (strCmd == "")

strCmd = "NOP" ;

strCmd = strCmd.PadRight(CMDLEN,FILLCHAR) ;

return WriteTextToSocket(s,strCmd) ;

}

/// <summary>

/// 將命令注釋寫到Socket中

/// </summary>

/// <param name="s">要發送命令注釋的Socket</param>

/// <param name="strInfo">要發送的命令注釋</param>

/// <returns>是否成功</returns>

public static bool WriteCommandDescToSocket(Socket s,string strDesc)

{

if (strDesc == "")

strDesc = "0" ;

strDesc = strDesc.PadRight(DESCLEN,FILLCHAR) ;

return WriteTextToSocket(s,strDesc) ;

}

/// <summary>

/// 發送可變信息的字節數

/// </summary>

/// <param name="s">要發送字節數的Socket</param>

/// <param name="iLen">字節數</param>

/// <returns>是否成功</returns>

public static bool WriteDynamicLenToSocket(Socket s,int iLen)

{

string strLen = iLen.ToString().PadRight(DYNAMICLENGTHLEN,FILLCHAR) ;

return WriteTextToSocket(s,strLen) ;

}

/// <summary>

/// 將緩存的指定部分發送到Socket

/// </summary>

/// <param name="s">要發送緩存的Socket</param>

/// <param name="buf">要發送的緩存</param>

/// <param name="iStart">要發送緩存的起始位置</param>

/// <param name="iCount">要發送緩存的字節數</param>

/// &lt;param name="iBlock">每次發送的字節說</param>

/// <param name="SendSuccess">每次發送成功後的回調函數</param>

/// <returns>是否發送成功</returns>

public static bool WriteBufToSocket(Socket s,byte [] buf,int iStart,int iCount,int iBlock,OnSend SendSuccess)

{

int iSended = 0 ;

int iSending = 0 ;

while(iSended<iCount)

{

if (iSended + iBlock <= iCount)

iSending = iBlock ;

else

iSending = iCount - iSended ;

s.Send(buf,iStart+iSended,iSending,SocketFlags.None) ;

iSended += iSending ;

if (ReadResponsionFromSocket(s)=="OK")

if (SendSuccess != null)

SendSuccess(iCount,iSended) ;

else

return false;

}

return true ;

}

/// <summary>

/// 將長度不固定文本發送到socket

/// </summary>

/// <param name="s">要發送文本的Socket</param>

/// <param name="strText">要發送的文本</param>

/// <param name="OnSendText">成功發送一部分文本後的回調函數</param>

/// <param name="settextlen">得到文本長度的回調函數</param>

/// <returns></returns>

public static bool WriteDynamicTextToSocket(Socket s,string strText,

OnSend OnSendText)

{

byte [] buf = Encoding.UTF8.GetBytes(strText) ;



int iLen = buf.Length ;

try

{

WriteDynamicLenToSocket(s,iLen) ;

return WriteBufToSocket(s,buf,0,iLen,DEALLEN,OnSendText) ;

}

catch(Exception err)

{

MessageBox.Show("發送文本失敗!"+err.Message) ;

return false ;

}

}

/// <summary>

/// 將文件寫到Socket

/// </summary>

/// <param name="s">要發送文件的Socket</param>

/// <param name="strFile">要發送的文件</param>

/// <returns>是否成功</returns>

public static bool WriteFileToSocket(Socket s,string strFile,

OnSend OnSendFile)

{

FileStream fs = new FileStream(strFile,FileMode.Open,FileAccess.Read,FileShare.Read) ;

int iLen = (int)fs.Length ;

WriteDynamicLenToSocket(s,iLen) ;

byte [] buf = new byte[iLen] ;

try

{

fs.Read(buf,0,iLen) ;

return WriteBufToSocket(s,buf,0,iLen,DEALLEN,OnSendFile) ;

}

catch(Exception err)

{

MessageBox.Show("發送文件失敗!"+err.Message) ;

return false ;

}

finally

{

fs.Close() ;

}

}

/// <summary>

/// 對方對自己消息的簡單回應

/// </summary>

/// <param name="s"></param>

/// <returns></returns>

public static string ReadResponsionFromSocket( Socket s)

{

byte [] bufCmd = new byte[RESPONLEN] ;

int iCount = s.Receive(bufCmd) ;

string strRespon = Encoding.UTF8.GetString(bufCmd,0,iCount) ;

return strRespon ;

}

/// <summary>

/// 從Socket讀取命令

/// </summary>

/// <param name="s">要讀取命令的Socket</param>

/// <returns>讀取的命令</returns>

public static string ReadCommandFromSocket( Socket s)

{

byte [] bufCmd = new byte[CMDLEN] ;

int iCount = s.Receive(bufCmd,0,CMDLEN,SocketFlags.Partial) ;

string strCommand = Encoding.UTF8.GetString(bufCmd,0,CMDLEN) ;

return strCommand = strCommand.TrimEnd(FILLCHAR) ;

}

/// <summary>

/// 讀取命令注釋

/// </summary>

/// <param name="s">要讀取命令注釋的Socket</param>

/// <returns>讀取的命令注釋</returns>

public static string ReadCommandDescFromSocket( Socket s)

{

byte [] bufCmd = new byte[DESCLEN] ;

int iCount = s.Receive(bufCmd,0,DESCLEN,SocketFlags.Partial) ;

string strCommand = Encoding.UTF8.GetString(bufCmd,0,DESCLEN) ;

return strCommand = strCommand.TrimEnd(FILLCHAR) ;

}

/// <summary>

/// 讀取可變部分的長度

/// </summary>

/// <param name="s">要讀取可變部分長度的Socket</param>

/// <returns>讀取的可變部分的長度</returns>

public static int ReadDynamicLenFromSocket( Socket s)

{

byte [] bufCmd = new byte[DYNAMICLENGTHLEN] ;

int iCount = s.Receive(bufCmd,0,DYNAMICLENGTHLEN,SocketFlags.Partial) ;

string strCommand = Encoding.UTF8.GetString(bufCmd,0,DYNAMICLENGTHLEN) ;

return int.Parse(strCommand.TrimEnd(FILLCHAR)) ;

}

/// <summary>

/// 讀取文本形式的可變信息

/// </summary>

/// <param name="s">要讀取可變信息的Socket</param>

/// <returns>讀取的可變信息</returns>

public static string ReadDynamicTextFromSocket( Socket s)

{

int iLen = ReadDynamicLenFromSocket(s) ;



byte [] buf = new byte[iLen] ;

string strInfo = "" ;



int iReceiveded = 0 ;

int iReceiveing = 0 ;

while(iReceiveded<iLen)

{

if (iReceiveded + DEALLEN <= iLen)

iReceiveing = DEALLEN ;

else

iReceiveing = iLen - iReceiveded ;

s.Receive(buf,iReceiveded,iReceiveing,SocketFlags.None) ;

CommunClass.WriteTextToSocket(s,"OK") ;

iReceiveded+= iReceiveing ;

}



strInfo = Encoding.UTF8.GetString(buf,0,iLen) ;



return strInfo ;

}

/// <summary>

/// 讀取文件形式的可變信息

/// </summary>

/// <param name="s">要讀取可變信息的Socket</param>

/// <param name="strFile">讀出後的文件保存位置</param>

/// <returns>是否讀取成功</returns>

public static bool ReadDynamicFileFromSocket( Socket s,string strFile)

{

int iLen = ReadDynamicLenFromSocket(s) ;

byte [] buf = new byte[iLen] ;

FileStream fs = new FileStream(strFile,FileMode.Create,FileAccess.Write) ;



try

{

int iReceiveded = 0 ;

int iReceiveing = 0 ;

while(iReceiveded<iLen)

{

if (iReceiveded + DEALLEN <= iLen)

iReceiveing = DEALLEN ;

else

iReceiveing = iLen - iReceiveded ;

s.Receive(buf,iReceiveded,iReceiveing,SocketFlags.None) ;

CommunClass.WriteTextToSocket(s,"OK") ;

iReceiveded+= iReceiveing ;

}

fs.Write(buf,0,iLen) ;

return true ;

} catch(Exception err)

{

MessageBox.Show("接收文件失敗"+err.Message) ;

return false ;

}

finally

{

fs.Close() ;

}

}

}//end class

}//end namespace

上面是俺的通訊基礎類,有了這個類,再進行發送接受還不是小菜一碟嗎?

未完待續

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved