将数据从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;}