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

來源:互聯網
上載者:User
最近一個項目要用到點對點檔案傳輸,俺就到處找資料寫程式,最後終於完成了,為了讓別人少走些彎路,俺決定將俺程式中最重要的部分貢獻出來,希望對大家有所協助。



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



一、通訊基類

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>

/// <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

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

未完待續




相關文章

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。