2010-08-02 104 views
0

我正在使用套接字。这里是我的代码(问题的描述是进一步):C#现有连接被远程主机强制关闭:套接字编程

客户端

public void ReadCallback(IAsyncResult ar) 
    { 
     int fileNameLen = 1; 
     String content = String.Empty; 
     StateObject state = (StateObject)ar.AsyncState; 
     Socket handler = state.workSocket; 

     int bytesRead = handler.EndReceive(ar); 
     if (bytesRead > 0) 
     { 

      if (flag == 0) 
      { 

       fileNameLen = BitConverter.ToInt32(state.buffer, 0); 
       string fileName = Encoding.UTF8.GetString(state.buffer, 4, fileNameLen); 
       receivedPath = mypath + @"XML\"; 
       if (!Directory.Exists(receivedPath)) 
       { 
        Directory.CreateDirectory(receivedPath); 
       } 
       receivedPath = receivedPath + fileName; 
       flag++; 

      } 
      if (flag >= 1) 
      { 

       BinaryWriter writer = new BinaryWriter(File.Open(receivedPath, FileMode.Append)); 
       if (flag == 1) 
       { 
        writer.Write(state.buffer, 4 + fileNameLen, bytesRead - (4 + fileNameLen)); 
        flag++; 
       } 
       else 
        writer.Write(state.buffer, 0, bytesRead); 
       writer.Close(); 
       handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, 
       new AsyncCallback(ReadCallback), state); 
      } 

     } 
     else 
     { 
      // Invoke(new MyDelegate(LabelWriter)); 
     } 
    } 

我就在这行错误:int bytesRead = handler.EndReceive(ar);

我如何才能避免这个错误?:An existing connection was forcibly closed by the remote host

服务器端

 public void ReadCallback(IAsyncResult ar) 
     { 
      try 
      { 

       int fileNameLen = 1; 
       String content = String.Empty; 
       StateObject state = (StateObject)ar.AsyncState; 
       Socket handler = state.workSocket; 
       string[] str = new string[2]; 
       str = handler.RemoteEndPoint.ToString().Split(':'); 
       IP = str[0].ToString(); 
       int bytesRead = handler.EndReceive(ar); 

       if (bytesRead > 0) 
       { 
        if (flag == 0) 
        { 
         fileNameLen = BitConverter.ToInt32(state.buffer, 0); 
         string fileName = Encoding.UTF8.GetString(state.buffer, 4, fileNameLen); 
         string[] getIP = new string[3]; 
         getIP = fileName.Split('_'); 
         #region Send Files in HandHeld 
         #region GetLoginFile 
         if (getIP[1].ToString().Equals("GetLoginFile")) 
         { 
          string getDirectory = @"Send_Hand_Held_Files\" + DateTime.Today.ToString("dd-MM-yyyy") + "\\" + getIP[0].ToString() + "\\XML"; 
          string strmyFile = getDirectory + "\\Login.xml"; 
          char[] delimiter = splitter.ToCharArray(); 
          split = strmyFile.Split(delimiter); 
          int limit = split.Length; 
          fName = split[limit - 1].ToString(); 

          byte[] LoginfileName = Encoding.UTF8.GetBytes(fName); //file name 

          byte[] fileData = File.ReadAllBytes(strmyFile); 

          byte[] LoginfileNameLen = BitConverter.GetBytes(LoginfileName.Length); //lenght of file name 
          clientData = new byte[4 + LoginfileName.Length + fileData.Length]; 

          LoginfileNameLen.CopyTo(clientData, 0); 
          LoginfileName.CopyTo(clientData, 4); 
          fileData.CopyTo(clientData, 4 + LoginfileName.Length); 

          handler.BeginSend(clientData, 0, clientData.Length, 0, new AsyncCallback(SendCallBack), handler); 
          //handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, 
          //new AsyncCallback(ReadCallback), state); 
          return; 
         } 
} 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 

      } 
      //SendData(IP); 
     } 

    private static void SendCallBack(IAsyncResult ar) 
     { 
      try 
      { 
       // Retrieve the socket from the state object. 
       Socket client = (Socket)ar.AsyncState; 

       // Complete sending the data to the remote device. 
       // int bytesSent = client.EndSend(ar); 
       //Console.WriteLine("Sent {0} bytes to server.", bytesSent); 

       // Signal that all bytes have been sent. 
       allDone.Set(); 

      } 
      catch (Exception e) 
      { 
       Console.WriteLine(e.ToString()); 
      } 
     } 
+0

严禁...不要强行关闭远程主机上的连接? – dtb 2010-08-02 15:54:46

+0

你是唯一访问服务器的客户端吗?难道服务器已超出允许的连接数?如果你有权访问服务器代码,你知道它是否被调用吗? – 2010-08-02 15:57:53

+0

还有其他可以访问服务器的客户端。 – 2010-08-02 16:04:41

回答

3

您从handler.EndReceive()获得例外。虽然目前还不清楚为什么您收到您提到的特定异常,投入生产时,此代码将在每次出现网络通信问题(这很常见)时抛出异常。

因此,您应该尝试围绕EndReceive()拨打电话。想想你的代码在连接失败或服务器死亡或其他情况时需要做什么。

然后您可以开始诊断特定问题。你还没有具体说明一件重要的事情:你是否偶尔得到这个错误或者你是否可以一直得到它?如果是前者,那么它可能只是普通的互联网连接波动。你的软件必须能够处理这些。如果是后者,那么我认为这听起来像是服务器上的问题。当您拨打BeginReceive()时,您的系统将开始等待服务器上的某些内容;如果那个“东西”是它接收到的数据,那么EndReceive()会成功,但如果这个“某事”是服务器已经关闭连接,你的回调仍然会被调用,然后EndReceive()会抛出相关的SocketException。这是设计的,因为几乎没有其他方法可以与代码通信,即服务器已关闭连接。

编辑:看起来像你的服务器代码需要同样的错误处理:其EndReceive()通话同样容易发生如果客户关闭连接抛出异常。 (我知道你有一个尝试/抓住周围的大事情,但它输出一个MessageBox ...这是不会在服务器上运行良好,除非你想要有人坐在那里所有的时间点击所有的确定按钮...)

+0

我几乎每次都收到错误 – 2010-08-02 16:39:10

+0

因此?我已经回答了。 – Timwi 2010-08-02 16:45:17

0

根据您的错误,我不确定问题出在您的代码上,它可能在服务器上。除了添加一些状态检查来验证handler.EndReceive(ar)将返回一些有用的信息之外,您可能需要检查服务器本身(或者要求维护它的人员这样做)查看为什么它会关闭您的连接。

最后,问题代码可能在您的初始代码中,而不是在这一块:例如,如果对服务器的初始调用过长并导致超时或死锁。

+0

我发布服务器端代码too.kindly帮助我。 – 2010-08-02 16:08:35

相关问题