所以我開始用套接字和異步讀取它們。異步套接字讀取
第一個問題是什麼這之間的區別:
socket.BeginReceive(readResult.Buffer, 0, SocketReadResult.BufferSize, 0, new AsyncCallback(ReadCallback), readResult);
和
socket.BeginReceive(readResult.Buffer, 0, SocketReadResult.BufferSize, 0, ReadCallback, readResult);
此外,由於這是我的回調函數,爲什麼例子,我讀有一個嘗試/抓住整個事情,當然你只需要圍繞socket.EndReceive()
呼叫嘗試/抓住?
public void ReadCallback(IAsyncResult ar)
{
try
{
var readResult = (SocketReadResult)ar.AsyncState;
var socket = readResult.Socket;
int bytesRead = socket.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
readResult.Text.Append(Encoding.ASCII.GetString(readResult.Buffer, 0, bytesRead));
// Get the rest of the data.
socket.BeginReceive(readResult.Buffer, 0, SocketReadResult.BufferSize, 0, new AsyncCallback(ReadCallback), readResult);
}
else
{
var newRead = new SocketReadResult(socket);
socket.BeginReceive(readResult.Buffer, 0, SocketReadResult.BufferSize, 0, new AsyncCallback(ReadCallback), newRead);
// All the data has arrived; put it in response.
if (readResult.Text.Length > 1) ((IMessageSender)this).RouteMessage(this, new MessageString(readResult.Text.ToString()));
}
}
catch (Exception e)
{
// TODO: manage this exception.
}
}
public struct SocketReadResult
{
StringBuilder Text;
Socket Socket;
byte[] Buffer;
public const int BufferSize = 1024;
public SocketReadResult(Socket s)
{
Socket = s;
Buffer = new byte[BufferSize];
Text = new StringBuilder();
}
}
最後所有的,你應該要正常關閉你叫socket.BeginReceive()
後的監聽器,你叫什麼功能,以及它是如何管理的?
至於爲什麼的try/catch是圍繞整個方法,ReadCallBack將異步可能在另一個線程或線程池進行。如果拋出一個異常,它將不會像您期望的那樣傳播回主線程,並且會最終導致進程崩潰。出於這個原因,你總是需要擁有任何可以在try/catch中完全包裝的獨立線程上運行的任何東西,因爲這是你最後一次正確處理錯誤的機會。 – Despertar
不同的簽名和異常處理實際上是兩個單獨的問題。你不應該在同一個問題中提問。選擇一個或另一個,然後編輯另一個(如果需要,將其作爲新問題發佈)。 – Servy
我沒有明白爲什麼你要讀取甚至當bytesRead == 0在其他部分? –