引言
自.NET Framework 2.0 版本開始新增了一個SendFile方法,此方法可以方便的發送指定路徑的文件,今天給大家演示一個利用Socket.SendFile方法發送圖片的例子,希望能給剛剛接觸Socket編程的朋友一些幫助,效果圖:
SendFile詳細參數
Socket.SendFile 方法(String, Byte[], Byte[], TransmitFileOptions)
使用指定的TransmitFileOptions 值,將文件fileName 和數據緩沖區發送到連接的Socket 對象。
注意是連接的Socket對象,所以只適用於TCP協議的Socket連接。
參數
fileName
一個String,它包含要發送的文件的路徑和名稱。此參數可以為 空引用(在Visual Basic 中為Nothing)。
preBuffer
一個Byte 數組,包含發送文件前要發送的數據。此參數可以為 空引用(在Visual Basic 中為Nothing)。
postBuffer
一個Byte 數組,包含發送文件後要發送的數據。此參數可以為 空引用(在Visual Basic 中為Nothing)。
flags
一個或多個TransmitFileOptions 值。
詳細請參考:Socket.SendFile
Send和Receive
SendFile
/// <summary>
/// 發送指定文件
/// </summary>
/// <param name="filename">文件路徑</param>
public void SendFile(string filename)
{
FileInfo fi = new FileInfo(filename);
byte[] len = BitConverter.GetBytes(fi.Length);
//首先把文件長度發送過去
_client.BeginSendFile(filename,
len,
null,
TransmitFileOptions.UseDefaultWorkerThread,
new AsyncCallback(SendFileCallback),
null);
}
private void SendFileCallback(IAsyncResult iar)
{
_client.EndSendFile(iar);
}
ReceiveFile
public void BeginReceive()
{
byte[] buffer = new byte[8];
//由於long占8位字節,所以先獲取前8位字節數據
IAsyncResult iar = _client.BeginReceive(
buffer,
0,
buffer.Length,
SocketFlags.None,
null,
null);
int len = _client.EndReceive(iar);
int offset = 0;
int length = BitConverter.ToInt32(buffer, offset); //先獲取文件長度
ReceiveFile(length);
BeginReceive(); //繼續接收
}
public void ReceiveFile(long filelen)
{
MemoryStream ms = new MemoryStream();
int bytesRead = 0;
long count = 0;
byte[] buffer = new byte[8192];
while (count != filelen)
{
bytesRead = _client.Receive(buffer, buffer.Length, 0);
ms.Write(buffer, 0, bytesRead);
count += bytesRead;
}
ReceivedBitmap(new Bitmap(ms));
}
最後
SendFile方法雖然用起來非常的方便,但也有自身的優缺點
優點:發送文件時自動創建線程,即使發送大文件時也不會影響主線程運行,不用擔心發送過程的狀態,文件發送完成時會自動返回。
缺點:只能發送指定路徑的文件,發送過程中得不到已發送的流量,所以不能觀察其發送的狀態。
大家可以根據自己所設計的系統環境采用SendFile方法,雖然SendFile的缺點讓我們情難以堪,但是發送一些小文件還是很方便的,比如圖片,文本文檔等等。
附 http://www.BkJia.com/uploadfile/2011/1122/20111122024523982.zip