【问题标题】:Java Server to iOS app Stream: Not CorrectJava 服务器到 iOS 应用程序流:不正确
【发布时间】:2014-10-21 09:00:24
【问题描述】:

我有一个 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);
        }
    }
}

有人知道,怎么了? 谢谢你:)

【问题讨论】:

  • 您是否真的尝试将 java 对象 String 发送到您的 iOS 应用程序?听起来很大胆

标签: java ios networking stream


【解决方案1】:

您应该尝试使用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();
      }
}

【讨论】:

    猜你喜欢
    • 2014-02-21
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 2017-03-02
    相关资源
    最近更新 更多