2014-08-27 50 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

相关问题