2012-07-09 78 views
0

我對網絡編程有點新,並且遇到了一些麻煩。我正在Android設備上創建一個JSON對象,通過TCP連接到一個python服務器,併發送JSON字符串。連接被接受,但我不斷丟失字符串的結尾,所以Android設備和使用TCP的python服務器之間的數據丟失

json.loads(json_string) 

失敗。

下面是相關的Android代碼:

private class Worker implements Runnable 
{ 
    @Override 
    public void run() 
    { 
     //create the network socket 
     try 
     { 
      socket = new Socket(address, 4242); 
      Log.i(TAG, "timeout: " + socket.getSoTimeout()); 
     } 
     catch (IOException e) 
     { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 


     packets = new ArrayList<JSONObject>(); 
     for (jobs.moveToFirst(); jobs.isAfterLast() == false; jobs.moveToNext()) 
     { 
      String jobName = jobs.getString(jobs.getColumnIndex(JobMetaData.JobTableMetaData.JOB)); 

      Uri.Builder updated = new Uri.Builder(); 
      updated.scheme("content"); 
      updated.authority(JobMetaData.AUTHORITY); 
      updated.appendPath(jobName); 
      updated.appendPath("member"); 
      updated.appendPath(JobMetaData.MemberTableMetaData.CHANGED); 
      updated.appendPath("true"); 

      Cursor changed = getContentResolver().query(updated.build(), null, null, null, null); 

      Log.d(TAG, "number of members " + changed.getCount()); 

      //create a JSON object out of the editable properties 
      for (changed.moveToFirst(); changed.isAfterLast() == false; changed.moveToNext()) 
      { 
       JSONObject json = new JSONObject(); 

       for (String att : changed.getColumnNames()) 
       { 
        if (ListMetaData.validAtts.contains(att)) 
        { 
         try 
         { 
          json.put(att, changed.getString(changed.getColumnIndex(att))); 
         } 
         catch (JSONException e) 
         { 
          // TODO Auto-generated catch block 
          Log.d(TAG, "JSON exception in DatagramService"); 
          e.printStackTrace(); 
         } 
        } 
       } 

       //include the GUID and job name 
       //for identification 
       try 
       { 
        json.put(JobMetaData.MemberTableMetaData.GUID, 
          changed.getString(changed.getColumnIndex(JobMetaData.MemberTableMetaData.GUID))); 
        json.put(JobMetaData.JobTableMetaData.JOB, jobName); 
       } 
       catch (JSONException e) 
       { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

       packets.add(json); 
      } 
      changed.close(); 
     } 

     Log.d(TAG, "entering send loop"); 
     try 
     { 
      out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); 
      out.flush(); 
     } 
     catch (IOException e1) 
     { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 

     for (JSONObject packet : packets) 
     { 
      Log.d(TAG, "supposedly sending"); 
      try 
      { 
       //now write the data 
       Log.d(TAG, "packet string: " + packet.toString()); 
       out.write(packet.toString()); 
       out.flush(); 
      } 
      catch (IOException e) 
      { 

      } 

     } 

     try 
     { 
      out.write("Done"); 
      out.flush(); 
      out.close(); 
     } catch (IOException e) 
     { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     stopSelf(); 
    } 

而且我現在用的是測試服務器(用Python編寫的):

#!/usr/bin/env python 

import SocketServer 
import json 

class MemberUpdateHandler(SocketServer.BaseRequestHandler): 
    def setup(self): 
     print self.client_address, "connected" 

    def handle(self): 
     while True: 
      self.JSONString = self.request.recv(8192).strip() 
      if self.JSONString == "Done": 
       return 
      self.handleJSON() 
      self.update() 

    def handleJSON(self): 
     JSONMember = json.loads(self.JSONString) 
     print "GUID:", JSONMember['ManufacturingGUID'] 
     print "Weight:", JSONMember['Weight'] 

    def update(self): 
     print "do something here" 


if __name__ == "__main__": 
    ADDRESS = '' 
    PORT = 4242 
    HOST = (ADDRESS, PORT) 

    s = SocketServer.ThreadingTCPServer(HOST, MemberUpdateHandler) 
    s.serve_forever() 

這裏是正在發送的字符串(它是長):

{"DetailCheckedBy":"","SketchRight":"","DetailLength":"142.75","DetailedDate":"**NOT SET**","EngineerVerifiedBothConns":"False","HoldStatus":"Not held","RevisionLevel":"No Revision","MemberNumber":"28","RequestVerifySectionSize":"False","TieForcesRight":"False","InputBy":"","IFCFinishDate_4":"**NOT SET**","IFCFinishDate_5":"**NOT SET**","Weight":"438.408","IFCTaskUID_1":"","IFCFinishDate_1":"**NOT SET**","ErectorOrder":"","IFCFinishDate_2":"**NOT SET**","IFCFinishDate_3":"**NOT SET**","IFCTaskUID_4":"","IFCTaskUID_5":"","IFCTaskUID_2":"","SketchLeft":"","IFCTaskUID_3":"","ErectorSequences":"","ReasonRejected":"","MemberCategory":"","EngineerVerifiedLeftConn":"False","BarcodeId":"","ManufacturingGUID":"42bbf9cc-52da-4712-a5fc-e37c5a544c14","aess":"False","FabricationComplete":"**NOT SET**","UserComment2":"","UserComment3":"","LoadNumber":"","UserComment1":"","ErectionBolted":"**NOT SET**","RequestVerifyLength":"False","RequestVerifyGrade":"False","Painted":"False","HeatCertNumber":"","Route1Description":"","IsExisting":"No","ReceivedFromApproval":"**NOT SET**","BackCheckedBy":"","BatchNumber":"","CostCodeReference":"","PONumber":"","Piecemark":"B_25","ReleasedForFabrication":"**NOT SET**","MemberDescription":"BEAM","EngineerVerifiedMemberReady":"False","IFCTaskName_2":"","IFCTaskName_1":"","IFCTaskName_4":"","RequestVerifyMemberPosition":"False","IFCTaskName_3":"","Erected":"**NOT SET**","RevisionCheckedBy_3":"","IFCTaskName_5":"","RevisionCheckedBy_2":"","RevisionCheckedBy_1":"","EngineerVerifiedLeftComments":"","RequestVerifyLeftConnMaterial":"False","RequestEngineerVerify":"False","RevisionCheckedDate_3":"**NOT SET**","RevisionCheckedDate_2":"**NOT SET**","RevisionCheckedDate_1":"**NOT SET**","EngineerVerifiedLength":"False","BackCheckedDate":"**NOT SET**","SubmittedForApproval":"**NOT SET**","EngineerVerifiedSpecial":"False","CostCodeDescription":"","IFCStartDate_5":"**NOT SET**","TieForcesLeft":"False","Fireproofed":"False","ErectorAvailable":"False","RequestVerifyRightConnMaterial":"False","DetailCheckedDate":"**NOT SET**","ErectorNonSteelSupported":"False","BeamPent":"False","StockStatus":"","Sequence":"1","RequestVerifyLeftLoad":"False","DetailFinalCheckDate":"**NOT SET**","ErectorMemberPlaced":"**NOT SET**","InstanceStatus":"","EngineerVerifiedRightConn":"False","DateReceived":"**NOT SET**","MemberType":"Beam","ModelCheckDate":"**NOT SET**","ReasonForHold":"","EngineerVerifiedRightComments":"","ReceivedOnJobSite":"**NOT SET**","RequestVerifyRightLoad":"False","CostCodePrice":"0.0","NestStatus":"","DateDue":"**NOT SET**","ShopSequence":"","EngineerVerifiedSectionSize":"False","ActualLength":"144","InputDate":"**NOT SET**","ErectorCity":"Unknown","EngineerVerifiedSpecial_comments":"","Route4Description":"","EngineerVerifiedGrade":"False","RightLocation":"0.0xx144.0xx156.0xx","IFCFinishTime_2":"","IFCFinishTime_1":"","IFCFinishTime_4":"","Route3Description":"","IFCFinishTime_3":"","LoadStatus":"","ErectorLongitude":"","DateModelCompleted":"61299957600000","Grade":"##SEKRIT KODE!!##","IFCFinishTime_5":"","Route2Description":"","RequestVerifyCamber":"False","ProjectedFabricationComplete":"**NOT SET**","DetailedBy":"","DetailFinalCheckBy":"","Description":"W8x35","ProjectedShippedDate":"**NOT SET**","NestName":"","IFCStartDate_2":"**NOT SET**","IFCStartTime_1":"","IFCStartDate_1":"**NOT SET**","IFCStartDate_4":"**NOT SET**","IFCStartDate_3":"**NOT SET**","IFCStartTime_5":"","IFCStartTime_4":"","IFCStartTime_3":"","DateHeld":"**NOT SET**","IFCStartTime_2":"","LeftLocation":"0.0xx0.0xx156.0xx","Job":"Mobile_x_x_x_x_Demo_x_x_x_x_IN_x_x_x_x_2011","SpecialCutWeld":"False","RejectedBy":"","ErectionWelded":"**NOT SET**","RequestVerifyRightConnConfig":"False","Vendor":"","PackageNumber":"","RejectedByErector":"**NOT SET**","ModelCheckedBy":"","ApprovalStatus":"Not reviewed","RequestVerifyLeftConnConfig":"False","ErectorLatitude":"","LotName":"","ActualShipDate":"**NOT SET**","NestId":""} 

這是我從Python服務器出現錯誤:

ValueError: Unterminated string starting at: line 1 column 1435 (char 1435) 

這意味着串已被截斷爲:

{"DetailCheckedBy":"","SketchRight":"","DetailLength":"142.75","DetailedDate":"**NOT SET**","EngineerVerifiedBothConns":"False","HoldStatus":"Not held","RevisionLevel":"No Revision","MemberNumber":"28","RequestVerifySectionSize":"False","TieForcesRight":"False","InputBy":"","IFCFinishDate_4":"**NOT SET**","IFCFinishDate_5":"**NOT SET**","Weight":"438.408","IFCTaskUID_1":"","IFCFinishDate_1":"**NOT SET**","ErectorOrder":"","IFCFinishDate_2":"**NOT SET**","IFCFinishDate_3":"**NOT SET**","IFCTaskUID_4":"","IFCTaskUID_5":"","IFCTaskUID_2":"","SketchLeft":"","IFCTaskUID_3":"","ErectorSequences":"","ReasonRejected":"","MemberCategory":"","EngineerVerifiedLeftConn":"False","BarcodeId":"","ManufacturingGUID":"42bbf9cc-52da-4712-a5fc-e37c5a544c14","aess":"False","FabricationComplete":"**NOT SET**","UserComment2":"","UserComment3":"","LoadNumber":"","UserComment1":"","ErectionBolted":"**NOT SET**","RequestVerifyLength":"False","RequestVerifyGrade":"False","Painted":"False","HeatCertNumber":"","Route1Description":"","IsExisting":"No","ReceivedFromApproval":"**NOT SET**","BackCheckedBy":"","BatchNumber":"","CostCodeReference":"","PONumber":"","Piecemark":"B_25","ReleasedForFabrication":"**NOT SET**","MemberDescription":"BEAM","EngineerVerifiedMemberReady":"False","IFCTaskName_2":"","IFCTaskName_1":"","IFCTaskName_4":"","RequestVerifyMemberPosition":"False","IFCTaskName_3":"","Erected":"**NOT SET**","RevisionCheckedBy_3":"","IFCTaskName_ 

任何幫助將不勝感激。提前致謝。

更新:

我已更新代碼以反映我的修補程序。服務器收到的字符串現在是

{"DetailCheckedBy":"","SketchRight":"","DetailLength":"142.75","DetailedDate":"**NOT SET**","EngineerVerifiedBothConns":"False","HoldStatus":"Not held","RevisionLevel":"No Revision","MemberNumber":"28","RequestVerifySectionSize":"False","TieForcesRight":"False","InputBy":"","IFCFinishDate_4":"**NOT SET**","IFCFinishDate_5":"**NOT SET**","Weight":"438.408","IFCTaskUID_1":"","IFCFinishDate_1":"**NOT SET**","ErectorOrder":"","IFCFinishDate_2":"**NOT SET**","IFCFinishDate_3":"**NOT SET**","IFCTaskUID_4":"","IFCTaskUID_5":"","IFCTaskUID_2":"","SketchLeft":"","IFCTaskUID_3":"","ErectorSequences":"","ReasonRejected":"","MemberCategory":"","EngineerVerifiedLeftConn":"False","BarcodeId":"","ManufacturingGUID":"42bbf9cc-52da-4712-a5fc-e37c5a544c14","aess":"False","FabricationComplete":"**NOT SET**","UserComment2":"","UserComment3":"","LoadNumber":"","UserComment1":"","ErectionBolted":"**NOT SET**","RequestVerifyLength":"False","RequestVerifyGrade":"False","Painted":"False","HeatCertNumber":"","Route1Description":"","IsExisting":"No","ReceivedFromApproval":"**NOT SET**","BackCheckedBy":"","BatchNumber":"","CostCodeReference":"","PONumber":"","Piecemark":"B_25","ReleasedForFabrication":"**NOT SET**","MemberDescription":"BEAM","EngineerVerifiedMemberReady":"False","IFCTaskName_2":"","IFCTaskName_1":"","IFCTaskName_4":"","RequestVerifyMemberPosition":"False","IFCTaskName_3":"","Erected":"**NOT SET**","RevisionCheckedBy_3":"","IFCTaskName_5":"","RevisionCheckedBy_2":"","RevisionCheckedBy_1":"","EngineerVerifiedLeftComments":"","RequestVerifyLeftConnMaterial":"False","RequestEngineerVerify":"False","RevisionCheckedDate_3":"**NOT SET**","RevisionCheckedDate_2":"**NOT SET**","RevisionCheckedDate_1":"**NOT SET**","EngineerVerifiedLength":"False","BackCheckedDate":"**NOT SET**","SubmittedForApproval":"**NOT SET**","EngineerVerifiedSpecial":"False","CostCodeDescription":"","IFCStartDate_5":"**NOT SET**","TieForcesLeft":"False","Fireproofed":"False","ErectorAvailable":"False","RequestVerifyRightConnMaterial":"False","DetailCheckedDate":"**NOT SET**","ErectorNonSteelSupported":"False","BeamPent":"False","StockStatus":"","Sequence":"1","RequestVerifyLeftLoad":"False","DetailFinalCheckDate":"**NOT SET**","ErectorMemberPlaced":"**NOT SET**","InstanceStatus":"","EngineerVerifiedRightConn":"False","DateReceived":"**NOT SET**","MemberType":"Beam","ModelCheckDate":"**NOT SET**","ReasonForHold":"","EngineerVerifiedRightComments":"","ReceivedOnJobSite":"**NOT SET**","RequestVerifyRightLoad":"False","CostCodePrice":"0.0","NestStatus":"","DateDue":"**NOT SET**","ShopSequence":"","EngineerVerifiedSectionSize":"False","ActualLength":"144","InputDate":"**NOT SET**","ErectorCity":"Unknown","EngineerVerifiedSpecial_comments":"","Route4Description":"","EngineerVerifiedGrade":"False","RightLocation":"0.0xx144.0xx156.0xx","IFCFinishTime_2":"","IFCFinishTime_1":"","IFCFinishTime_4":"","Route3Description":"","IFCFinishTime_3":"","LoadStatus":"","ErectorLongitude":"","DateModelCompleted":"61299957600000","Grade":"##SEKRIT KODE!!##","IFCFinishTime_5":"","Route2Description":"","RequestVerifyCamber":"False","ProjectedFabricationComplete":"**NOT SET**","DetailedBy":"","DetailFinalCheckBy":"","Description":"W8x35","ProjectedShippedDate":"**NOT SET**","NestName":"","IFCStartDate_2":"**NOT SET**","IFCStartTime_1":"","IFCStartDate_1":"**NOT SET**","IFCStartDate_4":"**NOT SET**","IFCStartDate_3":"**NOT SET**","IFCStartTime_5":"","IFCStartTime_4":"","IFCStartTime_3":"","DateHeld":"**NOT SET**","IFCStartTime_2":"","LeftLocation":"0.0xx0.0xx156.0xx","Job":"Mobile_x_x_x_x_Demo_x_x_x_x_IN_x_x_x_x_2011","SpecialCutWeld":"False","RejectedBy":"","ErectionWelded":"**NOT SET**","RequestVerifyRightConnConfig":"False","Vendor":"","PackageNumber":"","RejectedByErector":"**NOT SET**","ModelCheckedBy":"","ApprovalStatus":"Not reviewed","RequestVerifyLeftConnConfig":"False","ErectorLatitude":"","LotName":"","ActualShipDate":"**NOT SET**","NestId":""}Done 

後面跟着亂七八糟的空白。足夠的gedit無法加載全部。向前邁出兩步。 :/

+0

我不明白你的意思。 – Lunchbox 2012-07-09 18:58:19

+0

請檢查此線程http://stackoverflow.com/questions/11325871/pycurl-only-geting-part-of-the-response或可能是這個幫助http://stackoverflow.com/questions/4709737/convert-a Python中的字符串到字典 – Hunt 2012-07-09 19:04:24

+0

您的應用程序需要使用原始套接字通信嗎?如果沒有,我會建議使用DefaultHttpClient的內置實現之一通過REST API進行通信:http://developer.android.com/reference/android/net/http/AndroidHttpClient.html或http:///developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html – twaddington 2012-07-09 21:39:50

回答

0

sizeof(int)在兩個設備上可能都不相同。所以如果你想傳遞一個二進制整數,你可能應該硬編碼一些東西。

如果你評估int('\ 001 \ 002 \ 003 \ 004 \ 005 \ 006 \ 007 \ 010'),你不可能得到你想要的東西,我相信這與你正在做的很接近在你的Python代碼中。一方面,這兩個設備的字節序可能不同,另一方面,int()想要評估ASCII或其他編碼,而不是原始的依賴於endian的整數。

在Python端,您可能會發現這個有用: http://stromberg.dnsalias.org/~strombrg/bufsock.html

我不知道你正在使用的out.write(),但在發送()的較低水平,沒有保證你的整個緩衝區將被寫入一個單一的send() - 它可以提前停止並返回多少被髮送。希望Java可以保護你不受bufsock爲python所做的細節。

+0

你提到的最後一件事對我來說是最大的問題。我無法將問題縮小到Java端或Python端。我不確定數據在哪裏被截斷。 – Lunchbox 2012-07-10 12:05:12

0

爲什麼你「假設」該字符串已被截斷? print它,看看它實際上是什麼。

此外,正在發送的字符串(因爲您發佈它)不包含在{},這意味着它是不正確的JSON ...我試圖複製/粘貼的解釋,這就提出了一個ValueError

ValueError: Extra data: line 1 column 17 - line 1 column 3952 (char 17 - 3952) 

我封閉它{}和它的工作。你應該嘗試看看你正在接收的字符串是在Python的一邊,然後你就可以真正看到發生了什麼。我還假設,既然你看到了「完成」發送,那麼內容應該已經完全發送。

+0

我打印出收到的字符串,這正是我在問題中的第二個字符串。另外,我從問題的字符串中刪除了{},但它們包含在原始代碼中。我不確定爲什麼我這麼做......我會編輯和修復。 此外,事實證明,「完成」從未收到。嘗試執行時造成的異常 json.loads(self.JSONString) 將服務器顛簸,再次等待連接。 – Lunchbox 2012-07-11 13:25:06

+0

噢,如果是這樣的話,那麼我的答案是毫無意義的:)我不知道我能幫得更多,比...... – jadkik94 2012-07-11 14:16:48