AsyncSocket writeData Terminator - flush

I am porting a Java middleware client to objC. The java client uses the java stream.write and stream.flush at the end of the send. For the java client to send to the Echo server I need to add the stream.writeBytes("\r\n"); followed by stream.flush for the server to bounce the message back.
I am using the asyncsocket to send messages to the middleware's server, but after successfully opening the socket, the middleware does not react to a message sent using
[socket writeData:sendData withTimeout:-1 tag:0];
Also the middleware does not react to the message in the buffer when the socket is closed.
I am currently using
[socket writeData:[AsyncSocket CRLFData] withTimeout:-1 tag:0];
to flush the socket

I know this will not be the last time an assumption will come back to byte me.
I assumed that the java.io write was the same as BSD send or sendto, but from other posts, I am now assuming that the java.io.DataOutputStream is actually similar to NSMutableData and the write is appendData. Which means that writeInt is an Endian function and flush is the actual send/sendto command.

Related

Difference between closing a socket and closing a network stream (System.Net.Sockets)

I have a proxy server implemented, after sending the final response to client if I directly close the socket (System.Net.Sockets TCPClient.Client.Close()) then client end receives connection aborted error but instead if I use System.Net.Sockets TCPClient.getStream().Close(), it works successfully.I want to understand what's the difference and why is client side receiving an error in the first scenario?
I would say, that Close of sockets is not trivial operation as most people think :)
First of all, you should understand the how the close should be done correctly. Basically, you have to consider that close is a kind of message like any other message sent out your socket. Or other words close() is an information on the other side of communication that the peer finished some kind of work.
Now the important thing to understand that having a TCP socket you can inform the peer that you finished sending or finished listening.
On this page, you can check out how it works in the background (note that ACK and FIN are IP layer messages so even using plain sockets implementation you will never see them): http://www.tcpipguide.com/free/t_TCPConnectionTermination-2.htm
So now the more practical step. Please consider that you have a client and server. The server needs to receive a message and close the connection. Please consider that client is just going to send a message and then closes the connection. If you will also consider that networks need some time to process your communication, you will realize that if you do it quickly, client will close the connection before server received your message. If you can the TCPClient.Client.Close() client will stop listening for anything (that means also for information about that the server closed the connection). So here comes the TCP stack to play (windows does it for you) - in case you will close this way the socket, TCP stack, needs to inform the server site that whatever server has sent goes to dump. So that's why you have an exception.
So the correct way is to:
inform the server that client finished sending any data (FIN)
wait until server confirms that he knows that client will not send any data (ACK)
now server should inform client that will stop sending data (FIN)
now the client can say - "ok I got it, I will not listen anymore" (ACK)
Anyway, the C# TCPClient seems to hide the logic of the background socket closing routine, but if you will not call the close sequence correct way, you'll end up with errors.
I hope that this little bit long explanation will help you understand how it works in the background and finally let you understand why.
It's also a good way to read more about TCP protocol details if you wish to learn more: http://www.tcpipguide.com/free/t_TCPIPTransmissionControlProtocolTCP.htm
I suppose that in order to close connection, you need to send some special bytes sequence. And looks like it is implemented only by tcpclient library , and not implemented by socket library. Probably something like Eof should be sent.
You may check it by some net traffic utilities like tcpdump.
Good luck!

Sending and receiving data over Internet

This question is not for a concrete implementation of how this is done. It is more about the concept and design of sending information over Internet with some kind of protocol - either TCP or UDP. I know only that sockets are needed, but I am wondering about the rest. For example after a connection is made and you send the information through that, but how does the other end listen for a specific port and does it listen constantly?
Is listening done in a background thread waiting for information to be received? (In order to be able to do other things/processing while waiting for information)
So in essence, I think a real world example of how such an application works on a high level would be enough to explain the data flow. For example sending files in Skype or something similar.
P.S. Most other questions on similar topics are about a concrete implementation or a bug that someone has.
What I currently do in an application is the following using POSIX sockets with the TCP Protocol:
Most important thing is: The most function are blocking functions. So when you tell your server to wait for client connection, the function will block until a connection is established (if you need a server that handles multiple clients at once, you need to use threading!)
Server listens for specific port until a client connects. After the connect, you will get a new socket file descriptor to communicate with the client whilst the initial socket can listen to new connections. My server then creats a new thread to handle that client whilst waiting for new connections on the initial socket. In the new thread the server waits for a request command from the Client (e.g. Request Login Token). After a request was received by the server, the server will gather its informations, packs it together using Googles Protocol Buffers and sends it to the client. The client now either tells the server to terminate the session (if every data is received by the client that it needs) or send another request.
Thats basically the idea in my server. The bigger problem is the way you transmit and receive data. E.g. you cant send structs or classes (at least not via C++) over the wire, you need some kind of serializer and you have to make sure the other part knows how much to receive. So what i do is, first send a 4byte integer over the wire containing the size of the incomming package, then send the package itself using a serializer (in my case Googles Protocol buffers). The other side waits for 4 byte to be available, knowing that this will be the size of the incomming package. After 4 bytes are received, the program waits for exact that amount of data being available on the socket, when available, read the data out of the buffer and deserialize it. When the socket is not receiving data for 30 seconds, trigger a timeout and terminate the connection.
What you always need to be aware of is the endianess of the systems. E.g. a big endian system (e.g. PowerPC) and a little endian system (e.g. x86) will have problems when you send an integer directly over the wire. For example a
0001
on the x86, is a
1000
on the Power PC, thus making a 8 out of a 1. So you should always use functions like ntohl, an htonl, which will convert data from and to host byte order from and to network byte order (network byte order is always big endian).
Hope this kind of helps. I could also provide some code to you if that would help.

Receiving TCP packets as messages instead of using gen_tcp:recv/2

I'm writing a distributed chat application in Erlang for my own learning/benefit. I have a client and a server which maintain a persistent TCP connection. The client initiates the connection using gen_tcp:connect/3. The server is actually distributed over several nodes.
The gen_tcp documentation says:
Packets can be sent to the returned socket Socket using send/2. Packets sent from the peer are delivered as messages:
{tcp, Socket, Data}
Because of this, my client is able to receive any data the server sends as a normal Erlang message. This is desirable for my application.
The problem is that I can't see any way to make the connection on the server act the same way. I would love it if my server could receive sent data as an Erlang message. This way, the server can send data (i.e. when another person in the chat room sends a message) while waiting for the client to send a message.
Is there any way to implement this behavior?
EDIT: I'm aware of prim_inet:async_accept/2, but I'd prefer a documented approach if possible.
Look at inet:setopts with option {active, once|true}. Good article about

Setting up the source Port/IP on an TCP/IP connection

I have setup a TCP/IP client/server connection that will open and close the connection every time a request is exchaged. It works perfectly; the client app opens the connection, sends the request and waits. The server application receives the request produces a response and sends it back and closes the connection. Cient and server apps do that hundreds of times.
Now I was trying to go to the next step: setup the source IP address and port.
The code was supposed to work on both Linux and Windows, so SO_BINDTODEVICE is out of question, since it is only supported on Linux/Unix.
I tried to bind the source port and ANYADRR on the client socket. And it works... For a while. Eventually it thorws error 10038. I've read over the internet several articles but without clear answer... The selection of the source IP remains unclear.
Please, note that I also have a UNICAST and MULTICAST mode on the same library (connectionless UDP communication modes), a sender and receiver, and I was able to setup the source port/IP on the MULTICAST mode, UNICAST I didn't try yet.
Anyway, anyone know anything that could be of help? I'm using WinSock 2.2 and trying to be as much as possible platform indemendent.
Winsock error 10038 is WSAENOTSOCK, which means you have a bug in your code somewhere. You are trying to do something with a SOCKET handle that is not pointing at a valid socket object. That has nothing to do with the bind() function itself. Either you are calling socket() and not checking its result for an error, or you are trying to use a SOCKET handle that has already been closed by your app, or you have a memory overflow somewhere that is corrupting your SOCKET handle.

How to use sockets in iOS?

I have to implement an iOS application, which connects to a web server and receives events from it, i.e. server long polling. I plan to use the AsyncSocket library.
My idea is to open a socket on the iPhone, send it to the server the first time I connect to it, and then listen infinitely to the socket and update the GUI accordingly to the events the server sends to it. Here are my questions:
Is this a correct approach and if not - how it should be done?
Can the server send data to the socket I give to it (as long as the socket is opened), if the iPhone and the server are on different networks, and the iPhone is on a local network?
Yes. 2. Yes.
On the fone, you will get information arriving in to the fone probably something like this:
-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData*)data withTag:(long)tag
{
[data getBytes:&getMe length:sizeof(CommProt)];
// do not forget to roll in the next read...
[sock readDataToLength:sizeof(CommProt) withTimeout:-1 tag:0];
// now parse that command
}
and on the fone you will send information from the fone quite likely something like this (there are a couple of different approaches)...
-(void) mySendStringData:(NSString *)sss
{
// so easy, thank goodness for AysncSocket
NSData* data = [sss dataUsingEncoding: NSASCIIStringEncoding];
[theSocket writeData:data withTimeout:0.5 tag:0];
[theSocket writeData:quickCR withTimeout:0.5 tag:0];
// (in the protocol at hand, we are using a delimiter on the end (a CR))
}
Note. It is possible this post i made could be helpful to you: it gives the lowdown on protocols in iOS:
Tablet(iPad/Android)-Server Communication Protocol
I hope it helps.
Conceivably this could help iPad and Arduino Integration and this secret knowledge could help Client/Server GKSessions Cheers