2013-07-02 38 views
0

我有一个套接字客户端应用程序,让“因为套接字未连接发送或接收数据被判无效的请求。”上mSocket.BeginReceiveWindows XP中套接字错误

public void Connect() 
    { 
     if (mPort == 0) throw new Exception("No ip set to client."); 
     mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
     mSocket.BeginConnect(mHost, mPort, new AsyncCallback(OnConnected), mSocket); 
     mReceiveBuffer = new byte[MAX_RECEIVE_BUFFER]; 
    } 


private void OnConnected(IAsyncResult ar) 
    { 
     try 
     { 
      mSocket.EndConnect(ar); 
      BeginReceive(); 
     } 
     catch 
     { 
      Disconnect(); 
     } 
    } 

     private void BeginReceive() 
    { 
     mSocket.BeginReceive(inBuffer, 0, 300, SocketFlags.None, new AsyncCallback(onDataRecieve), mSocket); 
    } 

错误抛出。这只发生在Windows XP上。有谁知道为什么发生这种情况?

+0

您可能要启用网络跟踪,以帮助调试:http://msdn.microsoft.com/en-us/library/a6sbz1dx.aspx –

回答

1

你没有检查结果。连接尝试失败,并且您的OnConnect在超时后触发。

下面是一个完整的工作示例。为我工作得很好,应该适合你。你会注意到我正在检查我是否实际连接,并且保持线程完成所有工作。

public class Program 
{ 
    static void Main(string[] args) 
    { 
     AsyncSocketTest test = new AsyncSocketTest(); 

     test.SocketTest(); 
    } 
} 

public class AsyncSocketTest 
{ 
    private Socket socket; 
    private byte[] buffer; 
    private volatile bool keepRunning; 

    public void SocketTest() 
    { 
     Console.Out.WriteLine("Starting connect..."); 
     Console.Out.Flush(); 

     buffer = new byte[65536]; 

     keepRunning = true; 

     // connect to antiduh.com's web server 
     socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
     socket.BeginConnect(IPAddress.Parse("129.21.49.41"), 80, new AsyncCallback(OnConnect), null); 

     // Keep the main thread alive while all of the async requests run. 
     while (keepRunning) { Thread.Sleep(500); } 

     Console.Out.WriteLine("Quitting."); 
     Console.Out.Flush(); 
    } 

    private void OnConnect(IAsyncResult result) 
    { 
     try 
     { 
      if (result.IsCompleted == false) 
      { 
       Console.Out.WriteLine("OnConnect got incomplete result: " + result); 
      } 
      else 
      { 
       socket.EndConnect(result); 

       if (result.IsCompleted == false) 
       { 
        Console.Out.WriteLine("OnConnect got incomplete result: " + result); 
       } 
       else 
       { 

        Console.Out.WriteLine("Sending..."); 
        byte[] requestBytes; 
        string requestString = 
         "GET/HTTP/1.1\n" + 
         "Host: antiduh.com\n" + 
         "\n"; 

        requestBytes = Encoding.ASCII.GetBytes(requestString); 
        socket.Send(requestBytes); 

        Console.Out.WriteLine("Starting receive..."); 
        socket.BeginReceive(
         buffer, 
         0, 
         buffer.Length, 
         SocketFlags.None, 
         new AsyncCallback(OnReceive), 
         null 
        ); 
       } 
      } 
     } 
     catch (Exception e) 
     { 
      Console.Out.WriteLine("Caught exception in OnConnect: " + e); 
     } 
     finally 
     { 
      Console.Out.Flush(); 
     } 
    } 

    private void OnReceive(IAsyncResult result) 
    { 
     int received = socket.EndReceive(result); 
     string responseStr; 

     Console.Out.WriteLine("Received data: Length: {0}. Data: \r\n\r\n", received); 
     Console.Out.Flush(); 

     responseStr = Encoding.ASCII.GetString(buffer, 0, received); 

     Console.Out.WriteLine(responseStr); 
     Console.Out.Flush(); 

     socket.Close(); 
     keepRunning = false; 
    } 
} 

输出:

Starting connect... 
Sending... 
Starting receive... 
Received data: Length: 1137. Data: 


HTTP/1.1 200 OK 
Date: Tue, 02 Jul 2013 12:58:19 GMT 
Server: Apache/2.2.24 (FreeBSD) PHP/5.4.16 SVN/1.8.0 mod_ssl/2.2.24 OpenSSL/1.0.1e DAV/2 
Last-Modified: Tue, 11 Jul 2006 05:03:19 GMT 
ETag: "352-418473fcd33c0" 
Accept-Ranges: bytes 
Content-Length: 850 
Content-Type: text/html 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<title>welcome to antiduh</title> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
<style type="text/css"> 
<!-- 
body { 
    background-color: #6666CC; 
} 
--> 
</style></head> 

<body> 
<img src="index.gif" alt="index of steak" width="912" height="528" border="0" align="middle" usemap="#Map"> 
<map name="Map"> 
    <area shape="rect" coords="234,97,392,132" href="about.htm" alt="about"> 
    <area shape="rect" coords="691,150,846,186" href="projects.htm" alt="projects"> 
    <area shape="rect" coords="740,363,884,399" href="links.htm" alt="links"> 
    <area shape="rect" coords="423,478,562,511" href="misc.htm" alt="misc"> 
    <area shape="rect" coords="37,292,175,324" href="resume.htm" alt="resume"> 
</map> 
</body> 
</html> 

Quitting. 
+0

的错误是瞬间。即使我用本地主机上的服务器尝试它,如果连接失败也没有机会,它仍然会给出错误。 –

+0

如果对方的端口未打开,您可能会主动拒绝另一端的连接。 – antiduh

+0

此外,用于启动Begin *方法的线程必须保持活动状态,否则它将取消所有异步调用。 [msdn上的BeginReceive](http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.beginreceive.aspx):“当给定线程发起的所有I/O被该线程取消退出。如果线程在操作完成前退出,则挂起的异步操作可能会失败。“ – antiduh