Java Socket Programming: TCP/UDP Fundamentals, InetAddress, URL, and Multithreaded Server‑Client Examples
This article provides a comprehensive guide to Java network programming, covering TCP/IP basics, socket concepts, InetAddress and URL APIs, detailed TCP and UDP client‑server implementations, multithreaded server handling, and practical code examples for building robust network applications.
Java was originally designed as a network programming language, offering strong support for socket communication that enables client‑server interaction. This tutorial introduces the fundamentals of computer networking, including IP addresses, protocols, ports, the TCP/IP five‑layer model, and how these elements combine to form a socket.
The Java platform provides several networking APIs:
InetAddress : Represents an IP address and offers methods to retrieve host names and address bytes.
URL : Uniform Resource Locator for accessing resources on the Internet.
Socket and ServerSocket : Classes for TCP communication.
DatagramSocket and DatagramPacket : Classes for UDP communication.
InetAddress example:
InetAddress address = InetAddress.getLocalHost();
address.getHostName(); // host name
address.getHostAddress(); // IP address
byte[] bytes = address.getAddress(); // byte array of IP
InetAddress address2 = InetAddress.getByName("otherHost");
InetAddress address3 = InetAddress.getByName("192.168.1.10");URL example:
URL baidu = new URL("http://www.baidu.com");
URL url = new URL(baidu, "/index.html?username=tom#test");
url.getProtocol(); // http
url.getHost(); // www.baidu.com
url.getPort(); // -1 (default)
url.getPath(); // /index.html
url.getFile(); // /index.html?username=tom
url.getRef(); // test
url.getQuery(); // username=tomFor TCP programming, the typical workflow is:
Create a ServerSocket on the server side and bind it to a port.
Call accept() to wait for client connections.
Obtain input and output streams from the resulting Socket to read and write data.
Close streams and sockets when communication ends.
Sample server‑side TCP code:
// Server side
ServerSocket serverSocket = new ServerSocket(10086);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
System.out.println("Server received: " + line);
}
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.write("Welcome!");
pw.flush();
// Close resources
pw.close();
br.close();
socket.close();
serverSocket.close();Client‑side TCP code mirrors the server steps, creating a Socket with the server’s address and port, sending data via an output stream, and reading the response via an input stream.
UDP communication uses DatagramSocket and DatagramPacket. The server creates a socket, receives a packet, processes the data, and sends a response packet back to the client’s address and port.
// UDP server example
DatagramSocket socket = new DatagramSocket(10010);
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String info = new String(buf, 0, packet.getLength());
System.out.println("Server received: " + info);
InetAddress clientAddr = packet.getAddress();
int clientPort = packet.getPort();
byte[] reply = "Welcome!".getBytes();
DatagramPacket replyPacket = new DatagramPacket(reply, reply.length, clientAddr, clientPort);
socket.send(replyPacket);
socket.close();To handle multiple clients concurrently, the server can spawn a new thread for each accepted Socket, allowing simultaneous communication while the main thread continues listening for new connections.
Important notes:
Adjust thread priorities appropriately to avoid performance degradation.
Closing the output stream of a socket also closes the socket; therefore, close the socket directly instead of individual streams.
When transmitting objects over TCP, consider Java serialization mechanisms.
File transfer over sockets requires careful handling of I/O streams.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
