Sockets in Java are a mechanism for creating network connections between different processes or machines. A socket is an endpoint for sending or receiving data across a network connection, and Java provides several classes and interfaces for working with sockets.
To use sockets in Java, we need to create a server and a client program. The server program waits for incoming connections and the client program initiates the connection to the server. Here is an example of a simple server program:
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(8000);
System.out.println("Server started");
while (true) {
Socket socket = server.accept();
System.out.println("Client connected: " + socket);
DataInputStream input = new DataInputStream(socket.getInputStream());
String message = input.readUTF();
System.out.println("Message from client: " + message);
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.writeUTF("Hello from server");
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, we create a ServerSocket object on port 8000 and wait for incoming connections using the accept() method. When a client connects, we create a Socket object and get the input and output streams for sending and receiving data. We then read a message from the client using a DataInputStream and send a response using a DataOutputStream. Finally, we close the socket.
Here is an example of a client program that connects to the server:
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8000);
System.out.println("Connected to server");
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.writeUTF("Hello from client");
DataInputStream input = new DataInputStream(socket.getInputStream());
String message = input.readUTF();
System.out.println("Message from server: " + message);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, we create a Socket object and connect it to the server using the server’s hostname and port number. We then get the input and output streams and send a message to the server using a DataOutputStream. We read the server’s response using a DataInputStream and close the socket.
Sockets can be used for a wide range of network communication tasks, such as file transfer, chat applications, and remote procedure calls. They provide a flexible and powerful mechanism for creating network connections in Java.