# Java Networking
Network programming refers to writing programs that run on multiple devices (computers) that are connected via a network.
The J2SE API in the `java.net` package contains classes and interfaces that provide low-level communication details. You can use these classes and interfaces directly to focus on solving problems without worrying about the communication details.
The `java.net` package provides support for two common network protocols:
* **TCP**: TCP (Transmission Control Protocol) is a connection-oriented, reliable, byte-stream-based transport layer communication protocol. The TCP layer sits above the IP layer and below the application layer. TCP ensures reliable communication between two applications. It is commonly used for Internet protocols, known as TCP/IP.
* **UDP**: UDP (User Datagram Protocol) is located in the transport layer of the OSI model. It is a connectionless protocol that provides datagrams for sending data between applications. Due to its lack of reliability and connectionless nature, applications using UDP typically must tolerate some lost, corrupted, or duplicate packets.
This tutorial primarily covers the following two topics.
* **Socket Programming**: This is the most widely used network concept, explained in great detail here.
* **URL Processing**: This part is covered in a separate section. Click here to learn more about (#).
* * *
## Socket Programming
Sockets use TCP to provide a communication mechanism between two computers. A client program creates a socket and attempts to connect to the server's socket.
When the connection is established, the server creates a Socket object. The client and server can now communicate by writing to and reading from the Socket objects.
The `java.net.Socket` class represents a socket, and the `java.net.ServerSocket` class provides a mechanism for server programs to listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two computers using sockets:
* The server instantiates a `ServerSocket` object, representing communication through a port on the server.
* The server calls the `accept()` method of the `ServerSocket` class, which waits until a client connects to the given port on the server.
* While the server is waiting, a client instantiates a `Socket` object, specifying the server name and port number to request a connection.
* The `Socket` constructor attempts to connect the client to the specified server and port. If communication is established, a `Socket` object is created on the client side to communicate with the server.
* On the server side, the `accept()` method returns a new socket reference on the server that is connected to the client's socket.
Once the connection is established, communication occurs using I/O streams. Each socket has an output stream and an input stream. The client's output stream connects to the server's input stream, and the client's input stream connects to the server's output stream.
TCP is a bidirectional communication protocol, so data can be sent simultaneously over both data streams. The following classes provide a complete set of useful methods for implementing sockets.
* * *
## Methods of the ServerSocket Class
Server applications use the `java.net.ServerSocket` class to obtain a port and listen for client requests.
The `ServerSocket` class has four constructors:
**No.** | **Method Description**
--- | ---
1 | **`public ServerSocket(int port) throws IOException`**
Creates a server socket bound to the specified port.
2 | **`public ServerSocket(int port, int backlog) throws IOException`**
Creates a server socket with the specified backlog and binds it to the specified local port number.
3 | **`public ServerSocket(int port, int backlog, InetAddress address) throws IOException`**
Creates a server with the specified port, listen backlog, and local IP address to bind to.
4 | **`public ServerSocket() throws IOException`**
Creates an unbound server socket.
Creating an unbound server socket. If the `ServerSocket` constructor does not throw an exception, it means your application has successfully bound to the specified port and is listening for client requests.
Here are some common methods of the `ServerSocket` class:
**No.** | **Method Description**
--- | ---
1 | **`public int getLocalPort()`**
Returns the port this socket is listening on.
2 | **`public Socket accept() throws IOException`**
Listens for and accepts a connection to this socket.
3 | **`public void setSoTimeout(int timeout)`**
Enables/disables `SO_TIMEOUT` with the specified timeout value in milliseconds.
4 | **`public void bind(SocketAddress host, int backlog)`**
Binds the `ServerSocket` to a specific address (IP address and port number).
* * *
## Methods of the Socket Class
The `java.net.Socket` class represents the socket used by both the client and server to communicate with each other. A client obtains a `Socket` object by instantiating it, while a server obtains a `Socket` object through the return value of the `accept()` method.
The `Socket` class has five constructors:
**No.** | **Method Description**
--- | ---
1 | **`public Socket(String host, int port) throws UnknownHostException, IOException`**
Creates a stream socket and connects it to the specified port number on the specified host.
2 | **`public Socket(InetAddress host, int port) throws IOException`**
Creates a stream socket and connects it to the specified port number on the specified IP address.
3 | **`public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException`**
Creates a socket and connects it to the specified remote port on the specified remote host.
4 | **`public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException`**
Creates a socket and connects it to the specified remote port on the specified remote address.
5 | **`public Socket()`**
Creates an unconnected socket using the system-default `SocketImpl`.
When the `Socket` constructor returns, it doesn't simply instantiate a `Socket` object; it actually attempts to connect to the specified server and port.
Below are some methods of interest. Note that both the client and server have a `Socket` object, so either side can call these methods.
**No.** | **Method Description**
--- | ---
1 | **`public void connect(SocketAddress host, int timeout) throws IOException`**
Connects this socket to the server with a specified timeout value.
2 | **`public InetAddress getInetAddress()`**
Returns the address of the socket's connection.
3 | **`public int getPort()`**
Returns the remote port this socket is connected to.
4 | **`public int getLocalPort()`**
Returns the local port this socket is bound to.
5 | **`public SocketAddress getRemoteSocketAddress()`**
Returns the address of the endpoint this socket is connected to, or `null` if it is not connected.
6 | **`public InputStream getInputStream() throws IOException`**
Returns the input stream of this socket.
7 | **`public OutputStream getOutputStream() throws IOException`**
Returns the output stream of this socket.
8 | **`public void close() throws IOException`**
Closes this socket.
* * *
## Methods of the InetAddress Class
This class represents an Internet Protocol (IP) address. Below are some useful methods for Socket programming:
**No.** | **Method Description**
--- | ---
1 | **`static InetAddress getByAddress(byte[] addr)`**
Returns an `InetAddress` object given the raw IP address.
2 | **`static InetAddress getByAddress(String host, byte[] addr)`**
Creates an `InetAddress` given the hostname and IP address.
3 | **`static InetAddress getByName(String host)`**
Determines the IP address of a host, given the host's name.
4 | **`String getHostAddress()`**
Returns the IP address string in textual presentation.
5 | **`String getHostName()`**
Gets the host name for this IP address.
6 | **`static InetAddress getLocalHost()`**
Returns the local host.
7 | **`String toString()`**
Converts this IP address to a `String`.
* * *
## Socket Client Example
The following `GreetingClient` is a client program that connects to a server using a socket, sends a request, and then waits for a response.
## GreetingClient.java File Code:
```java
import java.net.*;
import java.io.*;
public class GreetingClient
{
public static void main(String []args)
{
String serverName = args;
int port = Integer.parseInt(args);
try
{
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
* * *
## Socket Server Example
The following `GreetingServer` program is a server-side application that uses a `Socket` to listen on a specified port.
## GreetingServer.java File Code:
```java
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + "nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String []args)
{
int port = Integer.parseInt(args);
try
{
Thread t = new GreetingServer(port);
t.run();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
Compile the above two Java files and execute the following command to start the server, using port 6066:
```bash
$ javac GreetingServer.java
$ java GreetingServer 6066
Waiting for client on port 6066...
Open a new command window and execute the following command to start the client:
```bash
$ javac GreetingClient.java
$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066
Goodbye!
π Categories
- β‘ JavaScript (1589)
- π PHP (872)
- π Python3 (810)
- π HTML (691)
- βοΈ C# (650)
- π Python (594)
- β Java (552)
- βοΈ PyTorch (534)
- π§ Linux (472)
- βοΈ C (432)
- π¦ jQuery (406)
- π¨ CSS (377)
- π XML (259)
- π¦ jQuery UI (231)
- π― Bootstrap (220)
- βοΈ C++ (215)
- π °οΈ Angular (205)
- π HTML DOM (201)
- π΄ Redis (188)
- π Web Building (142)
- π Vue.js (141)
- π R (131)
- πΌ Pandas (124)
- ποΈ SQL (105)
- βοΈ Docker (86)
- βοΈ TypeScript (73)
- βοΈ Highcharts (70)
- π AI Agent (70)
- βοΈ React (68)
- π Node.js (65)
- βοΈ Machine Learning (60)
- π Git (59)
- π΅ Go (58)
- π Markdown (58)
- π’ NumPy (55)
- π§ͺ Flask (54)
- βοΈ Scala (53)
- ποΈ SQLite (52)
- π JSTL (52)
- βοΈ VS Code (51)
- π MongoDB (49)
- π Perl (48)
- π Ruby (47)
- π Matplotlib (47)
- βοΈ Uncategorized (46)
- π Swift (46)
- ποΈ PostgreSQL (46)
- βοΈ Data Structures (46)
- π Playwright (46)
- π iOS (45)
- ποΈ MySQL (44)
- βοΈ LangChain (43)
- π FastAPI (40)
- βοΈ Ionic (38)
- π Design Patterns (37)
- βοΈ Eclipse (37)
- π¨ CSS3 (34)
- π Lua (34)
- βοΈ Codex (34)
- πΈ Django (32)
- βοΈ OpenCV (32)
- π Rust (31)
- π JSP (31)
- βοΈ Claude Code (31)
- π Pillow (30)
- βοΈ OpenCode (28)
- π AI Skills (27)
- π Flutter (26)
- π Maven (26)
- π¨ Tailwind CSS (25)
- π§ TensorFlow (25)
- π Servlet (24)
- π Dart (23)
- π Assembly (23)
- βοΈ Memcached (22)
- βοΈ SVG (22)
- βοΈ Electron (22)
- π NLP (22)
- π Regex (21)
- π Android (20)
- π£ Kotlin (19)
- π Julia (19)
- π SOAP (17)
- π Selenium (17)
- π PowerShell (17)
- π Sass (16)
- π HTTP (16)
- π Zig (15)
- π AI (15)
- π AJAX (14)
- π Swagger (14)
- βοΈ Scikit-learn (13)
- βοΈ ECharts (13)
- βοΈ Chart.js (13)
- βοΈ Cursor (13)
- βοΈ SciPy (12)
- π RDF (12)
- π Ollama (12)
- π Next.js (12)
- π Plotly Dash (12)
- π JSON (11)
- π RESTful API (11)
- π WSDL (9)
- βοΈ CMake (8)
- π Firebug (7)
- π Nginx (6)
- βΈοΈ Kubernetes (6)
- π Jupyter (6)
- π LaTeX (4)
- π UniApp (4)
- ποΈ SQL Server (1)
YouTip