socket : Java Glossary


Sockets let you send raw streams of bytes back and forth between two computers, giving you fairly low-level access to the TCP/IP (Transmission Control Protocol/Internet Protocol) protocol. See the File I/O Amanuensis for sample code to do that. In TCP/IP each computer has a name, such as However, various TCP/IP programs could be running on that computer. Each Socket gets a assigned a number called a port. The HTTP (Hypertext Transfer Protocol) server would usually be assigned 80. DbAnywhere is usually 8889. This way you can specify which service on the local or remote machine you want to connect with. The Socket is specified like this:
Flush Flow Control
Blocking Read Graceful Shutdown
Timeouts Learning More
Disconnet Detection Links
Server Side Socketing


If you write to a Socket, you usually need to call flush to force the data out onto the net. If you fail to do that, you could wait forever for a response because your complete query was never sent. You don’t need flush if you are sending a steady stream of data that will push earlier data out onto the net.

Blocking Read

If you read from a Socket, you can hang waiting forever if you use a blocking read. Socket.setSoTimeout controls the timeout. The read will eventually die when the Socket connection fails. This will happen when:


Java offers Socket.setSoTimeout to control how long you are willing to wait for a read to complete and Socket.setSoLinger to control how long it lingers, (waits to close when there are still unsent data). When you shutdown, the other end should continue to read any buffered data to let the other end close before closing itself. setSoTimeout has no effect on how long you are willing to wait for a write (how long you are willing to wait for the other end to accept data), just on how long you are willing to wait for the other end to produce data.

To add to the misery, Windows partially ignores the timeout. On connect, the JVM (Java Virtual Machine) tries to resolve the hostname to IP/port. Windows tries a netbios ns query on UDP (User Datagram Protocol) port 137 with a timeout of 1.5 seconds, ignores any ICMP (Internet Control Message Protocol) port unreachable packets and repeats this two more times, adding up to a value of 4.5 seconds. I suggest putting critical hostnames in your HOSTS file to make sure they are resolved quickly. Another possibility is turning off NETBIOS altogether and running pure TCP/IP on your LAN (Local Area Network).

Disconnect Detection

Since TCP/IP sends no packets except when there is traffic, without Socket.setKeepAlive( true ), it has no way of noticing a disconnect until you start trying to send (or to a certain extent receive) traffic again. Java has the Socket.setKeepAlive( true ) method to ask TCP/IP to handle heartbeat probing without any data packets or application programming. Unfortunately, you can’t tell it how frequently to send the heartbeat probes. If the other end does not respond in time, you will get a socket exception on your pending read. Heartbeat packets in both directions let the other end know you are still there. A heartbeat packet is just an ordinary TCP/IP ACK packet without any piggybacking data.

When the applications are idling, your applications could periodically send tiny heartbeat messages to each other. The receiver could just ignore them. However, they force the TCP/IP protocol to check if the other end is still alive. These are not part of the TCP/IP protocol. You would have to build them into your application protocols. They act as are-you-still-alive? messages. I have found Java’s connection continuity testing to be less that 100% reliable. My bullet-proof technique to detect disconnect is to have the server send an application-level heartbeat packet if it has not sent some packet in the last 30 seconds. It has to send some message every 30 seconds, not necessarily a dummy heartbeat packet. The heartbeat packets thus only appear when the server is idling. Otherwise normal traffic acts as the heartbeat. The Applet detects the lack of traffic on disconnect and automatically restarts the connection. The downside is your applications have to be aware of these heartbeats and they have to fit into whatever other protocol you are using, unlike relying on TCP/IP level heartbeats.

However, it is simpler to use the built-in Socket.setKeepAlive( true ) method to ask TCP/IP to handle the heartbeat probing without any data packets or application programming. Each end with nothing to say just periodically sends an empty data packet with its current sequence, acknowledgement and window numbers.

The advantage of application level heartbeats is they let you know the applications at both ends are alive, not just the communications software.

Server Side Socketing

For a server to accept connections from the outside world, first it opens a ServerSocket on a port, but not connected to any client in particular.

ServerSocket serverSocket = new ServerSocket( port );

Then it calls accept, which blocks until a call comes in.

Socket clientSocket = serverSocket.accept();

At that point a new ordinary Socket gets created that is connected to the incoming caller. Usually the server would spin off a Thread, or assign a Thread from a pool to deal with the new Socket and loop back to do another accept.

You can set up your miniature server even if you don’t have a domain name. They can get to you by name: ip:port e.g. :2222. Even if your are behind a firewall, you use the external facing IP (Internet Protocol) of the firewall. You must then configure your firewall to let incoming calls through and to direct them to the correct server on the lan.

Flow Control

With Socket.setReceiveBufferSize() you can hint to the underlying OS (Operating System) how much to buffer up incoming data. It is not obligated to listen to you. Don’t confuse this with the buffer on the BufferedInputStream. This is the lower level buffer on the raw socket. Large buffers are not always desirable. Using small buffers can tell the other end you are getting behind and it won’t send data as quickly. If the data is real time and the amount of data sent is variable depending on how fast you process it, large buffers mean you can get way behind and never catch up.

There is a mysterioous method Socket.setTcpNoDelay( true ) to disable Nagle’s algorithm. As is typical, there is no explanation what Nagle’s algorinthm is. My TCP/IP text book makes no mention of it. If you are dealing with near real-time data then you may want to look into disabling Nagle’s algorithm. That algorithm attempts to ensure that TCP doesn’t send lots of undersized IP packets by buffering-up submitted data and keeping it for typically for a few milliseconds to see if you are going to give it some more data that could go into the same packet. I am not sure if flush is sufficient to send a packet on its way immediately.

Graceful Shutdown

If you simply close a socket, you can lose data that were previously sent but which have not yet been delivered. You may chop things off in mid message. So, how to shut down gracefully? My approach is this. When the client wants to shut down, it sends a close message. The server echos it back and on receipt of the close message, the client closes the socket. That way the client is guaranteed to be unhooked from waiting on a read and you are guaranteed the server and client each recieved the last remaining messages before the socket was closed.

Learning More

Oracle’s Javadoc on Sockets class : available:
Oracle’s Javadoc on ServerSockets class : available:

CPU socket
Dyn: three free services of interest to people who host webservers on their home machines
File I/O Amanuensis: shows you how to code client side Sockets
HTTP Client
JavaSock: native code libraries to extend Socket
Networking Properties
QuickDNS download
QuickDNS manual
Sun Tutorial on Networking

This page is posted
on the web at:

Optional Replicator mirror
on local hard disk J:

Canadian Mind Products
Please the feedback from other visitors, or your own feedback about the site.
Contact Roedy. Please feel free to link to this page without explicit permission.

Your face IP:[]
You are visitor number