Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Acknowlegement in TCP communication in Java

Tags:

java

sockets

I have written a socket program in Java. Both server and client can sent/receive data to each other. But I found that if client sends data to server using TCP then internally TCP sends acknowledgement to the client once the data is received by the server. I want to detect or handle that acknowledgement. How can I read or write data in TCP so that I can handle TCP acknowledgement. Thanks.

like image 878
Sunil Kumar Sahoo Avatar asked Jun 08 '10 12:06

Sunil Kumar Sahoo


3 Answers

This is simply not possible, even if you were programming in C directly against the native OS sockets API. One of the points of the sockets API is that it abstracts this away for you.

The sending and receiving of data at the TCP layer doesn't necessarily correlate with your Java calls to send or receive data. The data you send in one Java call may be broken into several pieces which may be buffered, sent and received independently, or even received out of order.

See here for more discussion about this.

like image 51
Eric Petroelje Avatar answered Nov 08 '22 22:11

Eric Petroelje


Any data sent over a TCP socket is acknowledged in both directions. Data sent from client to server is the same as data sent from server to client as far as TCP wire communications and application signaling. As @Eric mentions, there is no way to get at that signaling.

It may be that you are talking about timing out while waiting for the response from the server. That you'd like to detect if a response is taking too long. Is it possible that the client's message is larger than the server's response so the buffering is getting in the way of the response but not the initial request? Have you tried to use non-blocking sockets?

You might want to take a look at the NIO code if you have not already done so. It has a number of classes that give you more fine grained control over socket communications.

like image 43
Gray Avatar answered Nov 08 '22 20:11

Gray


This is not possible in pure Java since Java's network API all handles socket, which hides all the TCP details.

You need a protocol that can handle IP-layer data so you can get TCP headers. DLPI is the most popular API to do this,

http://www.opengroup.org/onlinepubs/9638599/chap1.htm

Unfortunately, there is not Java implementation of such network. You have to use native code through JNI to do this.

like image 1
ZZ Coder Avatar answered Nov 08 '22 22:11

ZZ Coder