Java Networking: Introduction
Java has a reasonably easy-to-use builtin networking API which makes it easy to communicate via TCP/IP sockets or UDP sockets over the internet. TCP is typically used more often than UDP, but both options are explained in this tutorial.
There are two other tutorials here at tutorials.jenkov.com that are relevant to this Java networking tutorial. These are:
NOTE: This text uses SVG diagrams which not all browsers can show natively. If you cannot see any of the diagrams, and you are using Internet Explorer, you should install the Adobe SVG Reader Plugin. Firefox 3.0.5+ and Chrome users should be fine without this plugin.
Java TCP Networking Basics
Typically a client opens a TCP/IP connection to a server. The client then starts to communicate with the server. When the client is finished it closes the connection again. Here is an illustration of that:
A client may send more than one request through an open connection. In fact, a client can send as much data as the server is ready to receive. The server can also close the connection if it wants to.
Java Socket's and ServerSocket's
When a client wants to open a TCP/IP connection to a server, it does so using a Java Socket. The socket is told what IP address and TCP port to connect to and the rest is done by Java.
If you want to run a server that listens for incoming connections from clients on some TCP port, you have to use a Java ServerSocket. When a client connects via a client socket to a server's ServerSocket, a Socket is assigned on the server to that connection. The client and server now communicates Socket-to-Socket.
Socket's and ServerSocket's are covered in more detail in later texts.
Java UDP Networking Basics
UDP works a bit differently from TCP. Using UDP there is no connection between the client and server. A client may send data to the server, and the server may (or may not) receive this data. The client will never know if the data was received at the other end. The same is true for the data sent the other way from the server to the client.
Because there is no guarantee of data delivery, the UDP protocol has less protocol overhead.
There are several situations in which the connectionless UDP model is preferable
over TCP. These are covered in more detail in the text on Java's UDP
Java Networking Tutorial TOC
Here is a list of the topics covered in this tutorial trail on Java Networking / Sockets:
|Java Networking Introduction|
|URL + URLConnection|
|URL's to Local Files|