2010-05-18 79 views
13

我試圖從Java桌面應用程序向J2ME應用程序發送圖像。問題是,我得到這個異常:java.net.SocketException:軟件導致連接中止:套接字寫入錯誤

java.net.SocketException: Software caused connection abort: socket write error 

我已經看了看周圍上了網,雖然這個問題並不罕見,我無法找到一個具體的解決方案。在傳輸圖像之前,我將圖像轉換爲字節數組。這些都是在桌面應用程序,並在J2ME分別

public void send(String ID, byte[] serverMessage) throws Exception 
    {    
     //Get the IP and Port of the person to which the message is to be sent. 
     String[] connectionDetails = this.userDetails.get(ID).split(","); 
     Socket sock = new Socket(InetAddress.getByName(connectionDetails[0]), Integer.parseInt(connectionDetails[1])); 
     OutputStream os = sock.getOutputStream(); 
     for (int i = 0; i < serverMessage.length; i++) 
     { 
      os.write((int) serverMessage[i]); 
     } 
     os.flush(); 
     os.close(); 
     sock.close(); 
    } 

    private void read(final StreamConnection slaveSock) 
    { 
     Runnable runnable = new Runnable() 
     { 
      public void run() 
      { 
       try 
       { 
        DataInputStream dataInputStream = slaveSock.openDataInputStream(); 
        int inputChar; 
        StringBuffer results = new StringBuffer(); 
        while ((inputChar = dataInputStream.read()) != -1) 
        { 
         results.append((char) inputChar); 
        } 
        dataInputStream.close(); 
        slaveSock.close(); 
        parseMessage(results.toString()); 
        results = null; 
       } 

       catch(Exception e) 
       { 
        e.printStackTrace(); 
        Alert alertMsg = new Alert("Error", "An error has occured while reading a message from the server:\n" + e.getMessage(), null, AlertType.ERROR); 
        alertMsg.setTimeout(Alert.FOREVER); 
        myDisplay.setCurrent(alertMsg, resultScreen); 
       } 
      } 
     }; 
     new Thread(runnable).start(); 
    } 

我在局域網發送消息找到了方法,我沒有問題,當我發的不是圖片簡短的文本信息。另外,我使用wireshark,似乎桌面應用程序只發送部分消息。任何幫助將不勝感激。此外,一切工作在J2ME模擬器上。

回答

5

請參考答案Official reasons for "Software caused connection abort: socket write error"

編輯

,我不認爲還有更多的是一般可以說了,似乎沒有要什麼異常有關代碼會導致連接中止。然而,我會注意到:

  • 將字節轉換爲write調用的整數是不必要的。它會自動升級。
  • 使用write(byte[])而不是write(int)會更好(更簡單,可能在網絡流量方面更高效)。
  • 接收端假定每個字節表示一個完整的字符。這可能是不正確的,這取決於發送方如何形成要傳輸的字節,並且
  • 通過發送字節計數開始是一個好主意,以便接收方能夠判斷髮送方發送之前是否有問題整個字節數組。
+0

我已經經歷了這些答案。我查看了Windows事件日誌,但沒有看到任何相關的事件,儘管我沒有經歷過這些日誌的經驗。其次,我也嘗試在shutdownOutput()中添加;但仍然無濟於事。 最後,我從J2ME應用程序中得到一個錯誤,說該套接字已關閉。 – npinti 2010-05-18 23:08:19

+0

呃...我不知道如何,但我似乎現在可以得到它的工作。我嘗試將轉換替換爲整數部分,但是這完全打亂了我的應用程序,完全禁用它。我試着今天發送它,它工作。我的猜測是,這是一些外部原因,可能是路由器重新啓動或其他。 – npinti 2010-05-19 08:17:11

相關問題