bytesWritten, but other device never receives NSStreamEventHasBytesAvailable event - ios

I have set up a Bonjour network between an iPhone and a Mac.
The user chooses the iPhone’s net service in a table presented in the Mac, and a pair of streams are created and opened on both sides.
The iPhone starts by sending a code (an integer) to the Mac. The Mac successfully receives it.
After a pause for user input and processing, the Mac initiates sending a code to the iPhone:
NSInteger bytesWritten = [self.streamOut write:buffer maxLength:sizeof(uint8_t)];
// bytesWritten is 1.
But the iPhone never gets an NSStreamEventHasBytesAvailable event. I double-checked just before this point, and streamStatus on the iPhone’s NSInputStream is 2, which is NSStreamStatusOpen, as it should be.
Any ideas what could be wrong?
Update: I ran a test in which the Mac was the first to send an integer to the iPhone. Again, I got a bytesWritten of 1 from the Mac’s output stream, but the iPhone never got a NSStreamEventHasBytesAvailable event.
So there must be something wrong with the iPhone’s input stream. But I doublechecked:
iPhone’s self.streamIn is correctly typed as NSInputStream in the h file
iPhone receives 2 NSStreamEventOpenCompleted events, and I check the class of the stream arg. One isKindOfClass:[NSOutputStream class], the other isn’t.
iPhone never receives NSStreamEventEndEncountered, NSStreamEventErrorOccurred, or NSStreamEventNone.
As noted above, following the Mac’s write to output stream, iPhone’s input stream status is 2, NSStreamStatusOpen.
Here is the code used to create the iPhone's input stream. It uses CF types because it's done in the C-style socket callback function:
CFReadStreamRef readStream = NULL;
CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, &readStream, NULL);
if (readStream) {
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
server.streamIn = (NSInputStream *)readStream;
server.streamIn.delegate = server;
[server.streamIn scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
if ([server.streamIn streamStatus] == NSStreamStatusNotOpen)
[server.streamIn open];
CFRelease(readStream);
}
Update2: Info responsive to alastair’s comment:
Socket Options
The retain, release, and copyDescription callbacks are set to NULL. The optionFlags are set to acceptCallback.
Socket Creation
Here’s the method used to set up the socket on both the iPhone and the Mac, complete with my commented attempts to figure out what is actually going on in this code, which was adapted from various tutorials and experiments (which worked):
/**
Socket creation, port assignment, socket scheduled in run loop.
The socket represents the port on this app's end of the connection.
*/
- (BOOL) makeSocket {
// Make a socket context, with which to configure the socket.
// It's a struct, but doesn't require "struct" prefix -- because typedef'd?
CFSocketContext socketCtxt = {0, self, NULL, NULL, NULL}; // 2nd arg is pointer for callback function
// Make socket.
// Sock stream goes with TCP protocol, the safe method used for most data transmissions.
// kCFSocketAcceptCallBack accepts connections automatically and presents them to the callback function supplied in this class ("acceptSocketCallback").
// CFSocketCallBack, the callback function itself.
// And note that the socket context is passed in at the end.
self.socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, (CFSocketCallBack)&acceptSocketCallback, &socketCtxt);
// Do socket-creation error checking.
if (self.socket == NULL) {
// alert omitted
return NO;
}
// Prepare an int to pass to setsockopt function, telling it whether to use the option specified in arg 3.
int iSocketOption = 1; // 1 means, yes, use the option
// Set socket options.
// arg 1 is an int. C-style method returns native socket.
// arg 2, int for "level." SOL_SOCKET is standard.
// arg 3, int for "option name," which is "uninterpreted." SO_REUSEADDR enables local address reuse. This allows a new connection even when a port is in wait state.
// arg 4, void (wildcard type) pointer to iSocketOption, which has been set to 1, meaning, yes, use the SO_REUSEADDR option specified in arg 3.
// args 5, the size of iSocketOption, which can now be recycled as a buffer to report "the size of the value returned," whatever that is.
setsockopt(CFSocketGetNative(socket), SOL_SOCKET, SO_REUSEADDR, (void *)&iSocketOption, sizeof(iSocketOption));
// Set up a struct to take the port assignment.
// The identifier "addr4" is an allusion to IP version 4, the older protocol with fewer addresses, which is fine for a LAN.
struct sockaddr_in addr4;
memset(&addr4, 0, sizeof(addr4));
addr4.sin_len = sizeof(addr4);
addr4.sin_family = AF_INET;
addr4.sin_port = 0; // this is where the socket will assign the port number
addr4.sin_addr.s_addr = htonl(INADDR_ANY);
// Convert to NSData so struct can be sent to CFSocketSetAddress.
NSData *address4 = [NSData dataWithBytes:&addr4 length:sizeof(addr4)];
// Set the port number.
// Struct still needs more processing. CFDataRef is a pointer to CFData, which is toll-free-bridged to NSData.
if (CFSocketSetAddress(socket, (CFDataRef)address4) != kCFSocketSuccess) {
// If unsuccessful, advise user of error (omitted)…
// ... and discard the useless socket.
if (self.socket)
CFRelease(socket);
self.socket = NULL;
return NO;
}
// The socket now has the port address. Extract it.
NSData *addr = [(NSData *)CFSocketCopyAddress(socket) autorelease];
// Assign the extracted port address to the original struct.
memcpy(&addr4, [addr bytes], [addr length]);
// Use "network to host short" to convert port number to host computer's endian order, in case network's is reversed.
self.port = ntohs(addr4.sin_port);
printf("\nUpon makeSocket, the port is %d.", self.port);// !!!:testing - always prints a 5-digit number
// Get reference to main run loop.
CFRunLoopRef cfrl = CFRunLoopGetCurrent();
// Schedule socket with run loop, by roundabout means.
CFRunLoopSourceRef source4 = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0);
CFRunLoopAddSource(cfrl, source4, kCFRunLoopCommonModes);
CFRelease(source4);
// Socket made
return YES;
}
Runloop Scheduling
Yes, all 4 streams are scheduled in the runloop, all using code equivalent to what I posted in the first update above.
Runloop Blocking:
I’m not doing anything fancy with synchronization, multiple threads, NSLocks, or the like. And if I set a button action to print something to the console, it works throughout — the runloop seems to be running normally.
Update4, Stream Ports?
Noa's debugging suggestion gave me the idea to examine the stream properties further:
NSNumber *nTest = [self.streamIn propertyForKey:NSStreamSOCKSProxyPortKey]; // always null!
I had assumed that the streams were hanging onto their ports, but surprisingly, nTest is always null. It's null in my apps, which would seem to point to a problem -- but it's also null in a tutorial app that works. If a stream doesn't need to hang onto its port assignment once created, what is the purpose of the port property?
Maybe the port property is not accessible directly? But nTest is always null in the following, too:
NSDictionary *dTest = [theInStream propertyForKey:NSStreamSOCKSProxyConfigurationKey];
NSNumber *nTest = [dTest valueForKey:NSStreamSOCKSProxyPortKey];
NSLog(#"\tInstream port is %#.", nTest); // (null)
nTest = [dTest valueForKey:NSStreamSOCKSProxyPortKey];
NSLog(#"\tOutstream port is %#.", nTest); // (null)

The trouble was this line:
CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, &readStream, NULL);
This would have been OK if I were only receiving data on the iPhone end. But I was creating a pair of streams, not just an input stream, so below this code I was creating a write stream:
CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, NULL, &writeStream);
The CFStream Reference says, “If you pass NULL [for readStream], this function will not create a readable stream.” It doesn’t say that if you pass NULL, you’ll render a previously created stream inoperable. But that is apparently what happens.
One strange artifact of this setup was that if I opened the streamIn first, I would have the opposite problem: The iPhone would get hasByteAvailable events, but never a hasSpaceAvailable event. And as noted in the question, if I queried the streams for their status, both would return NSStreamStatusOpen. So it took a long time to figure out where the real mistake was.
(This sequential stream creation was an artifact of a test project I had set up months before, in which I tested data moving in only one direction or the other.)
SOLUTION
Both streams should be created as a pair, in one line:
CFStreamCreatePairWithSocket(kCFAllocatorDefault, socketNativeHandle, &readStream, &writeStream);

Related

lwIP mqtt connection error on stm32f4 discovery

I am trying to use lwIP for a client, which sends data to mosquitto broker on stm32f407 discovery.
Mqtt application is implemented at lwIP. I just use them like that at main after initializing.
mqtt_client_t static_client;
Afterwards, with USART interrupt, I call
example_do_connect(&static_client); example_publish(&static_client,0);
Which calls those functions:
{
struct mqtt_connect_client_info_t ci;
err_t err;
/* Setup an empty client info structure */
memset(&ci, 0, sizeof(ci));
/* Minimal amount of information required is client identifier, so set it here */
ci.client_id = "lwip_test";
ci.client_user = NULL;
ci.client_pass = NULL;
/* Initiate client and connect to server, if this fails immediately an error code is returned
otherwise mqtt_connection_cb will be called with connection result after attempting
to establish a connection with the server.
For now MQTT version 3.1.1 is always used */
err = mqtt_client_connect(client, &serverIp, MQTT_PORT, mqtt_connection_cb, 0, &ci);
/* For now just print the result code if something goes wrong*/
if(err != ERR_OK) {
}
}
and
void example_publish(mqtt_client_t *client, void *arg)
{
const char *pub_payload= "stm32_test";
err_t err;
u8_t qos = 2; /* 0 1 or 2, see MQTT specification */
u8_t retain = 0; /* No don't retain such crappy payload... */
err = mqtt_publish(client, "pub_topic", pub_payload, strlen(pub_payload), qos, retain, mqtt_pub_request_cb, arg);
if(err != ERR_OK) {
// printf("Publish err: %d\n", err);
err = ERR_OK;
}
}
/* Called when publish is complete either with sucess or failure */
static void mqtt_pub_request_cb(void *arg, err_t result)
{
if(result != ERR_OK) {
// printf("Publish result: %d\n", result);
}
}
I am able to ping board, my IP adress has been assigned in main by using IP_ADDR4(&serverIp, 192,168,2,97);
I've used all needed functions like MX_LWIP_Init(), MX_LWIP_Process() and actually i am even able to implement a TCP client, which is working nice. So internet connection is well, but I guess, there is a point that i missed in mqttclient. Callbacks is also have done by Erik Anderssen's guide.
When i try to subscribe to board's IP by using mosquitto, Error: no connection could be made because the target actively refused it. If you notice some point that i have missed or have an idea, please let me know.
Any help will appreciated, thanks in advance.
I had a similar problem that the server refused the connection when QoS (quality of service) was set to 2, but the server needed it to be 0. Try changing the parameter qos in the line in the connection callback to either 0 or 1:
err = mqtt_subscribe(mqtt.client, "topic", qos, MqttApp_SubscribeRequestCallback, arg);
Same applies to the parameter qos in the publish function:
change u8_t qos = 2; to u8_t qos = 0; (or 1 - whatever your server requires)
Hope it helps. Cheers.

How to find last relay node of a data packet in-transit?

I'm trying to implement a security mechanism in RPL. For this, I need to log where did a packet come from. For example, if a packet is transmitted from A-->B-->C-->D, I want to find out at C that the packet came through B, and similarly for D.
I've added some code in uip6.c file to pull up the sender address from packetbuffer, but it is always null.
I'm storing the last node address and the time when the complete packet was received. These are the data structures.
struct packet_time_entry {
linkaddr_t *source;
uint32_t time;
};
MEMB(packet_time_mem, struct packet_time_entry, 16);
LIST(packet_time);
The main code I've written so far is this, in uip_process(), below line 1108 (master branch).
struct packet_time_entry *p = memb_alloc(&packet_time_mem);
p->time = clock_time();
linkaddr_copy(p->source, packetbuf_addr(PACKETBUF_ADDR_SENDER));
struct packet_time_entry *i;
for (i = list_head(packet_time); i != NULL; i = list_item_next(i)) {
if (linkaddr_cmp(i->source, p->source))
list_remove(packet_time, i);
}
list_add(packet_time, p);
PRINTF("Entry ");
PRINTLLADDR((uip_lladdr_t*) p->source); // always NULL
PRINTF("| %lu", p->time);
PRINTF("\n");
I expect it to give me the address from packetbuf, but it's always NULL. Also, I suspect it is run only at the destination node, but not at the intermediate nodes.
You can DEBUG the execution. For that just set DEBUG_NONE TO DEBUG_PRINT in uip6.c and then parse the serial log for finding the path taken by the packet.

Is there a way to make separate DNS requests for IPv4 and IPv6 in swift or ObjC

What I have so far is:
void startQueryIPv4(const char *hostName){
printf("startQueryIPv4");
DNSServiceRef serviceRef;
DNSServiceGetAddrInfo(&serviceRef, kDNSServiceFlagsForceMulticast, 0, kDNSServiceProtocol_IPv4, hostName, queryIPv4Callback, NULL);
DNSServiceProcessResult(serviceRef);
DNSServiceRefDeallocate(serviceRef);
}
static void queryIPv4Callback(DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *hostname, const struct sockaddr *address, uint32_t ttl, void *context){
printf("queryIPv4Callback");
if (errorCode == kDNSServiceErr_NoError) {
printf("no error");
char *theAddress = NULL;
switch(address->sa_family) {
case AF_INET: {
struct sockaddr_in *addr_in = (struct sockaddr_in *)address;
theAddress = malloc(INET_ADDRSTRLEN);
inet_ntop(AF_INET, &(addr_in->sin_addr), theAddress, INET_ADDRSTRLEN);
break;
}
case AF_INET6: {
struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)address;
theAddress = malloc(INET6_ADDRSTRLEN);
inet_ntop(AF_INET6, &(addr_in6->sin6_addr), theAddress, INET6_ADDRSTRLEN);
break;
}
default:
break;
}
printf("IP address: %s\n", theAddress);
free(theAddress);
} else {
printf("%d", errorCode);
}
}
But the callback is never called.
In the console I get this error: TIC Read Status [9:0x0]: 1:57
ObjectiveC is not my power but I had to mess with it. Any help will be appreciated.
Inasmuch as Objective-C is a true superset of C and Darwin is certified compatible with SUS 3, your Objective-C program for iOS should be able to use the C interface to the system's name resolver: getaddrinfo(). You can use the third argument to this function to specify that you want only IPv4 results (or only IPv6 results).
Things of which you should be aware:
this is of course a synchronous interface; if you want asynchronous then you'll need to arrange for that yourself.
getaddrinfo() allocates and returns a linked list of addresses, so
in principle, you might need to check more than one
you need to free the list after you're done with it via freeaddrinfo()
The reason you aren't getting a callback is that you aren't using a dispatch queue. The DNSServiceGetAddrInfo API is asynchronous. If you are doing this on an Apple device, you want something more like this:
void startQueryIPv4(const char *hostName) {
printf("startQueryIPv4");
DNSServiceRef serviceRef;
DNSServiceGetAddrInfo(&serviceRef, kDNSServiceFlagsForceMulticast, 0, kDNSServiceProtocol_IPv4, hostName, queryIPv4Callback, NULL);
main_queue = dispatch_get_main_queue();
DNSServiceSetDispatchQueue(sdref, main_queue);
dispatch_main();
}
Note that dispatch_main() is the main event loop for libdispatch: if you want to do other stuff, you need to schedule it in the dispatch loop, because dispatch_main() will not return.
In your original code you called DNSServiceRefDeallocate(), but you can't do that until you want to stop the query. If you call it right after you start the query, it will cancel the query. So e.g. you could call it from the callback.
However, a better flow would be to do a long-lived query (kDNSServiceFlagsLongLivedQuery) so that you get an update whenever the information changes. Of course you'd then need to change the host you're connecting to, so only do this if your application will be connected for an extended period.
Additionally, you may get more than one answer. If you do, it may be that some answers work to connect, and others don't. So you might like to accumulate answers and try each one, rather than giving up if the first answer you get doesn't work. The callback will include the kDNSServiceFlagsMoreComing flag if there is more data coming immediately. Each time the callback is called, it will get one answer (or an indication that the query has failed in some way).
Of course, this is a fairly low-level API. If you want to make your life a bit easier, you should use Network Framework. Network Framework does the "happy eyeballs" part for you—trying each response until it gets a connection, and returning you the connection it gets, canceling the others.
But you didn't ask about that, so I won't go into details here.

How to ensure server-side CFSocket listens after application resigns and returns to active back again?

I have an iOS application that follows roughly the following steps:
Opens a listening socket.
Accepts a single client connection.
Performs data exchanges to/from client.
When it receives a "resign active" event, it closes and releases all resources associated to the client and server sockets (i.e. invalidates and releases all run loop sources, read/write streams and sockets themselves).
Upon resuming active, it brings back up the listening socket to continue communications (the client will keep trying to reconnect until it is able to, after the iOS app resigned active in step #4).
Whenever a connection does take place between client and server, what I am seeing after step #5 is that the application resumes without being able to reopening the server socket for listening. In other words, even though everything is released in step #5, the application is not able to rebind and listen at the socket address. What's worse, no errors can be detected in the CFSocket API calls while trying to setup the listening socket back again.
If, on the other hand the iOS application resigns active and resumes back again without previously receiving any connection, the client is then able to connect exactly once, until the application resigns and resumes again, in which case the same behaviour above can then be observed.
An example minimal application that illustrates this issue can be found in the following repository:
https://github.com/dpereira/cfsocket_reopen_bug
The most relevant source is:
#import "AppDelegate.h"
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
static void _handleConnect(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void* data, void* info)
{
NSLog(#"Connected ...");
close(*(CFSocketNativeHandle*)data);
NSLog(#"Closed ...");
}
#interface AppDelegate ()
#end
#implementation AppDelegate {
CFRunLoopSourceRef _source;
CFSocketRef _serverSocket;
CFRunLoopRef _socketRunLoop;
}
- (void)applicationWillResignActive:(UIApplication *)application {
CFRunLoopRemoveSource(self->_socketRunLoop, self->_source, kCFRunLoopCommonModes);
CFRunLoopSourceInvalidate(self->_source);
CFRelease(self->_source);
self->_source = nil;
CFSocketInvalidate(self->_serverSocket);
CFRelease(self->_serverSocket);
self->_serverSocket = nil;
CFRunLoopStop(self->_socketRunLoop);
NSLog(#"RELASED SUCCESSFULLY!");
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
CFSocketContext ctx = {0, (__bridge void*)self, NULL, NULL, NULL};
self->_serverSocket = CFSocketCreate(kCFAllocatorDefault,
PF_INET,
SOCK_STREAM,
IPPROTO_TCP,
kCFSocketAcceptCallBack, _handleConnect, &ctx);
NSLog(#"Socket created %u", self->_serverSocket != NULL);
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_len = sizeof(sin);
sin.sin_family = AF_INET;
sin.sin_port = htons(30000);
sin.sin_addr.s_addr= INADDR_ANY;
CFDataRef sincfd = CFDataCreate(kCFAllocatorDefault,
(UInt8 *)&sin,
sizeof(sin));
CFSocketSetAddress(self->_serverSocket, sincfd);
CFRelease(sincfd);
self->_source = CFSocketCreateRunLoopSource(kCFAllocatorDefault,
self->_serverSocket,
0);
NSLog(#"Created source %u", self->_source != NULL);
self->_socketRunLoop = CFRunLoopGetCurrent();
CFRunLoopAddSource(self->_socketRunLoop,
self->_source,
kCFRunLoopCommonModes);
NSLog(#"Registered into run loop");
NSLog(#"Socket is %s", CFSocketIsValid(self->_serverSocket) ? "valid" : "invalid");
NSLog(#"Source is %s", CFRunLoopSourceIsValid(self->_source) ? "valid" : "invalid");
}
#end
The full-blown app resides in: https://github.com/dpereira/conflux
Is there something wrong in the setup/teardown of the sockets (and related resources)?
The issue here is that the listening socket was going into TIME_WAIT and could not be bound to again while in that state.
Even though no errors are returned by the CFSocket API, if the same situation happens when using POSIX sockets an error takes place while trying to re-bind the socket.
The solution was to simply set the SO_REUSEADDR option for the socket just prior to re-binding the socket for listening.

Arduino WiFi shield post with header problems

I'm trying to do a post from the arduino wifi shield to my java servlet. The servlet functions with url get, and jquery post, but I can't sort the headers out in my arduino code. Any help will be greatly appreciated!
The server returns 200, but I'm not getting the payload "content" as value. I'm not exactly sure what I'm doing wrong but I'm pretty sure it's in how my headers are setup. I've spent the last two days trying to get it.
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "jesussavesforjust19.95"; // your network SSID (name)
char pass[] = "********"; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
IPAddress server(192,168,10,149); // numeric IP for Google (no DNS)
WiFiClient client;
void setup() {
Serial.begin(9600);
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.println("Attempting to connect to SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to wifi");
printWifiStatus();
sendData("0600890876");
}
void loop() {
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
if (client.available()) {
char c = client.read();
Serial.println(c);
}
//String dataString = "060088765";
// if you're not connected, and ten seconds have passed since
// your last connection, then connect again and send data:
if(!client.connected())
{
Serial.println();
Serial.println("disconnecting.");
client.stop();
//sendData(dataString);
for(;;)
;
}
}
// this method makes a HTTP connection to the server:
void sendData(String thisData) {
// if there's a successful connection:
Serial.println("send data");
if (client.connect(server, 8080)) {
String content = "value=0600887654";
Serial.println(content);
Serial.println("connected");
client.println("POST /hos HTTP/1.1");
client.println("Host:localhost");
client.println("Connection:Keep-Alive");
client.println("Cache-Control:max-age=0");
client.println("Content-Type: application/x-www-form-urlencoded\n");
client.println("Content-Length: ");
client.println(content.length());
client.println("\n\n");
client.println(content);
}
else {
// if you couldn't make a connection:
Serial.println("form connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.println("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.println("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.println("signal strength (RSSI):");
Serial.println(rssi);
Serial.println(" dBm");
}
Perhaps, some of your "Serial.println" and "client.println" commands should be "Serial.print" and "client.print" instead. For example:
client.print("Content-Length: ");
client.println(content.length());
would avoid adding a line break between the text and the number.
This is maybe more advice on an approach than an answer.
If I was doing something like this I would not start on the Arduino. The endless compile, download, run, look at print()'s would drive me crazy. I would fully prototype the client/server interaction in whatever you have at your fingertips, preferably something with a debugger. (Java, Python, PHP, VB, whatever you know that you can slap together)
Second, I would run Wireshark on the server so that I could see exactly what was being sent and responded.
Then I would port the same interaction over to the Arduino. Again inspect with Wireshark to confirm you are getting what you expected. If you send the same bytes, you should get the same response.
Even if you choose to implement straight on Arduino, consider having Wireshark to capture the actual network traffic.
With Wireshark, you might see that the Arduino println() is not sending the correct line end for the server.
Also, there is no guarantee that last println() is actually sent. The network stack implementation is free to buffer as it sees fit. You might need a flush(). A packet trace would show this.
With a packet capture you might find that time matters. In theory TCP is a stream and you should be able to send that POST data 1 character at a time in 1 packet and everything would work. But the Arduino might be so slow executing those println()'s by the server's standards that it times out. In such case you would see the server respond before the Arduino even finished sending.

Resources