Java Sockets provide a powerful mechanism for network communication between applications. They enable developers to create robust client-server systems and facilitate data transfer across networks.
Sockets are endpoints for communication between two machines. In Java, the java.net
package offers classes for socket programming, allowing applications to send and receive data over networks.
Socket
and ServerSocket
classes.DatagramSocket
and DatagramPacket
classes.Here's an example of a basic TCP server using Java Sockets:
import java.io.*;
import java.net.*;
public class SimpleServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5000);
System.out.println("Server is listening on port 5000");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received: " + inputLine);
out.println("Server: " + inputLine);
}
clientSocket.close();
}
}
}
Here's a corresponding client that connects to the server:
import java.io.*;
import java.net.*;
public class SimpleClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 5000);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello, Server!");
System.out.println("Server response: " + in.readLine());
socket.close();
}
}
As you become more comfortable with basic socket operations, you can explore advanced topics:
java.nio
package for scalable network applications.javax.net.ssl
package.Socket programming often involves other Java concepts:
By mastering Java Sockets, you'll be well-equipped to develop sophisticated networked applications, from chat systems to distributed computing platforms.