我使用VS 2008來實現一個從客戶端獲取套接字連接的服務器。 我爲此使用了MSDN示例代碼,它真的適合我第一次使用。 我的來自客戶端作者的信息是,在第一次請求之前,它嘗試握手,然後發送其第一個請求。我真的很好。 然後我發送響應到客戶端,並獲得它。 但現在我的問題開始: 客戶端開始發送請求,但我什麼都沒有! 我不確定我的實現,因爲在MSDN示例中只有一個請求。 任何人都可以解釋得到第一個請求和第二個請求之間應該有什麼區別?我應該爲每個請求使用Socket.Accept(),還是在從Socket.Accept()函數獲取了套接字後,我只需使用Socket.Receive()?套接字服務器沒有得到第二個請求
我的代碼是基於MSDN樣本是在這裏:
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
SocketError errorCode;
// An incoming connection needs to be processed.
while (true)
{
bytes =new byte[1024];
handler.ReceiveTimeout = 2000;
int bytesRec = handler.Receive(bytes,0,1024,0,out errorCode);
data +=Encoding.ASCII.GetString(bytes, 0, bytesRec);
Console.WriteLine("Text received : {0}", data);
string answer = "my answer to client";
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(answer);
handler.Send(msg);
}
我的結果是我第一次獲得bytesRec一些數據,並傳送給客戶端的響應。然後我再也沒有收到bytesRec的任何內容,但是由於超時錯誤,收到的內容會中止。
由於提前,
你介意格式化你的代碼,使它可讀嗎? –