简体   繁体   中英

Why I can't send the message to my java server via obj-c?

Here is the question. I open a socket from my java server, and send a UTF string using objective-c, it can't read. So, I am interested in what's going wrong??:

First here is the java code:

DataInputStream in = new DataInputStream( server.getInputStream()); System.out.println(in.readUTF()); //Just holding, can't print out

Full source code is here:

http://www.tutorialspoint.com/java/java_networking.htm

Then, is my iOS client source code:

NSString *requestStrFrmt = @"HEAD / HTTP/1.0\r\nHost: %@\r\n\r\n";

NSString *requestStr = [NSString stringWithFormat:requestStrFrmt, HOST];
NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding];

[asyncSocket writeData:requestData withTimeout:-1.0 tag:0];

Full source code for iOS client:

https://github.com/robbiehanson/CocoaAsyncSocket

The file path I quote: CocoaAsyncSocket / GCD / Xcode / SimpleHTTPClient / Mobile / SimpleHTTPClient / SimpleHTTPClientAppDelegate.m

I didn't do something fancy, just change the IP and port. And here is the output:

Waiting for client on port 7780... Just connected to /192.168.1.31:55207

Yes, they can connect together, but the server can't read the string I send.

The readUTF method expects to read the length of the string as a 16 bit big endian number before the string data. You'll have to either modify the client so it will send the length, or use another function to read the data in the server.

You seem to be making a http client and server, so you should use the second option and make the Java server read the request with the read method.

Besides, the http request headers should be encoded in iso-8859-1, preferably ASCII, so using the UTF-8 encoding is a mistake in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM