2014-08-27 46 views
0

我有一個Java服務器,並希望發送字符串消息到iOS應用程序。Java服務器到iOS應用程序流:不正確

發送理論上的作品,但我總是收到「¬í」在我的應用程序。我嘗試了不同的編碼,如ASCII,Unicode,UTF-16。

我的Java方法發送看起來是這樣的:

public void sendName(String str) { 
    try { 
     System.out.println("Send: "+str); 
     ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); 
     oos.writeObject(str.getBytes(StandardCharsets.US_ASCII)); 
    } catch (IOException ex) { 
    } 
} 

,我的目標C接收方法是這樣的:

- (void)readFromStream{ 
    uint8_t buffer[1024]; 
    int len; 
    NSMutableString *total = [[NSMutableString alloc] init]; 
    while ([inputStream hasBytesAvailable]) { 
     len = [inputStream read:buffer maxLength:sizeof(buffer)]; 
     if (len > 0) { 
      [total appendString: [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding]]; 
      NSLog(@"%@",total); 
     } 
    } 
} 

是否有人知道,什麼是錯? 謝謝:)

+0

你真的想java對象'String'發送到您的iOS應用?這聽起來很大膽 – ortis 2014-08-27 17:01:56

回答

0

您應該嘗試使用PrintStreamBufferedOutputStream而不是ObjectOutputStream。因爲ObjectOutputStream聽起來像是在發送對象String而不是字符串。

public void sendName(String str) 
{ 
    PrintStream ps = null; 
    try 
    { 
     System.out.println("Send: "+str); 
     ps = new PrintStream(s.getOutputStream()); 
     ps.println(str); 
     ps.flush(); 
    } catch (IOException ex) 
    { 
    } 
    finally 
    { 
     if(ps != null) 
     ps.close(); 
    } 
} 

public void sendName(String str) 
    { 
     BufferedOutputStream bos = null; 
     try 
     { 
      System.out.println("Send: "+str); 
      bos = new BufferedOutputStream(s.getOutputStream()); 
      bos.write(str.getBytes(StandardCharsets.US_ASCII)); 
      bos.flush(); 
     } catch (IOException ex) 
     { 
     } 
     finally 
     { 
      if(bos!= null) 
      bos.close(); 
     } 
} 
+0

超級,謝謝!現在它工作:) – Chromo 2014-08-27 17:42:36

相關問題