将数据从iOS发送到Java套接字服务器 [英] Sending Data from iOS to java socket server

查看:177
本文介绍了将数据从iOS发送到Java套接字服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个问题,为什么我这样发送数据

Hi I have the next issue, why when I send data like this

uint8_t buffer[11] = "I send this";

NSInteger nwritten = [outputStream write:buffer maxLength:sizeof(buffer)];

if (-1 == nwritten) {
    NSLog(@"Error writing to stream %@: %@", outputStream, [outputStream streamError]);
}else{
    NSLog(@"Wrote %i bytes to stream %@.", nwritten, outputStream);
}

在Java套接字服务器的另一端

in the other side in the java socket server

connection = new Socket(Constants.HOST, Constants.CHAT_LISTENER_PORT);
_in = new DataInputStream(connection.getInputStream());
String data = _in.readUTF();

但是没有任何东西看起来好像没有发送任何东西。

But nothing appear like as if it had not sent anything.

我读了很多,我发现问题来自于平台,因为java字节适用于big-endians和带小端的iOS,但我没有找到有关如何做到这一点的信息。

I read to much and I found the problem is from platforms because java byte works with big-endians and iOS with little-endians but I don't found information about how do to this.

uint8_t buffer [11] =我发送此信息; to big-Endians格式

请heellppp,谢谢。

Please heellppp, thanks.

对不起我的英语很好但是没有西班牙语:/ thaks。

Sorry my English is very but there is nothing in spanish :/ thaks.

推荐答案

在java代码的下一行的服务器端:

On the server side in the next Line in java code:

DataInputStream.readUTF();

这个.readUTF()期望一个UTF java原生类型与objective-c类型不一样,解决方案是发送字符串编码在UTF原生java这样。

this .readUTF() expect a UTF java native type what is not the same with objective-c type, and the solution was send the string codifying in UTF native java like this.

NSString *msg = @"initChat_";
NSString *messageToSend  = [NSString stringWithFormat:@"%@", msg];
NSData *data = [self convertToJavaUTF8:messageToSend];

int dataLenght = [data length];

int num = [outputStream write:(const uint8_t *)[data bytes] maxLength:dataLenght];


if (-1 == num) {
    NSLog(@"Error writing to stream %@: %@", outputStream, [outputStream streamError]);
}else{
    NSLog(@"Wrote %i bytes to stream %@.", num, outputStream);
}

魔术来自:

- (NSData*) convertToJavaUTF8 : (NSString*) str {
NSUInteger len = [str lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
Byte buffer[2];    
buffer[0] = (0xff & (len >> 8));
buffer[1] = (0xff & len);
NSMutableData *outData = [NSMutableData dataWithCapacity:2];
[outData appendBytes:buffer length:2];        
[outData appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
return outData;}

这篇关于将数据从iOS发送到Java套接字服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆