Socket programming
Socket programming in Java refers to the ability to create network communication between
two devices or applications using sockets. Sockets are endpoints for sending or receiving data
across a computer network. In Java, socket programming is primarily used for implementing
client-server communication, where one program (the server) provides services and another
program (the client) requests and uses those services.
Java provides a package called java.net that includes classes and interfaces for network
programming, including socket programming.
The basic steps involved in socket programming in Java are:
1. Server side
a) Import necessary packages
import java.io.*;
import java.net.*;
b) Create a server socket and bind it to a specific port
ServerSocket serverSocket = new ServerSocket(12345); // Port number
c) Accept incoming client connections
Socket clientSocket = serverSocket.accept();
d) Get input and output streams to send and receive data
InputStream input = clientSocket.getInputStream();
OutputStream output = clientSocket.getOutputStream();
2. Client side
a) Import necessary packages
import java.io.*;
import java.net.*;
b) Create a socket and connect it to the server’s IP address and port
Socket socket = new Socket("server_ip_address", 12345); // Replace with actual IP
c) Get input and output streams for communication
InputStream input = socket.getInputStream();
OutputStream output = socket.getOutputStream();
Socket programming in Java allows for various types of network applications, such as web
servers, chat applications, and file transfer protocols. It’s an essential concept in networking
and enables communication between different devices over a network.
Client Side Programming
In the case of client-side programming, the client will first wait for the server to start. Once the
server is up and running, it will send the requests to the server. After that, the client will wait
for the response from the server. So, this is the whole logic of client and server communication.
Now let’s see how to write a complete Java program to implement socket connection at the
client-side.
import java.net.*;
import java.io.*;
public class ClientSide {
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
public ClientSide(String address, int port) {
try {
socket = new Socket(address, port);
System.out.println("Connected");
input = new DataInputStream(System.in);
out = new DataOutputStream(socket.getOutputStream());
} catch(UnknownHostException u) {
System.out.println(u);
} catch(IOException i) {
System.out.println(i);
}
String line = "";
while (!line.equals("Over")) {
try {
line = input.readLine();
out.writeUTF(line);
} catch(IOException i) {
System.out.println(i);
}
}
try {
input.close();
out.close();
socket.close();
} catch(IOException i) {
System.out.println(i);
}
}
public static void main(String args[]) {
ClientSide client = new ClientSide("127.0.0.1", 5000);
}
}
Server Side Programming
Basically, the server will instantiate its object and wait for the client request. Once the client
sends the request, the server will communicate back with the response.
The two main types of sockets used in Java (to code server-side application):
1. ServerSocket: This class is used on the server side to create a socket that listens for
incoming client connections. It waits for clients to connect to it and then establishes a
communication channel between the server and the client.
2. Socket: This class is used on the client side to create a socket that connects to the
server’s listening socket. Once the connection is established, data can be exchanged
between the client and the server.
Now let’s see how to write a complete Java program to implement socket connection at server
side.
import java.net.*;
import java.io.*;
public class ServerSide {
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
public ServerSide(int port) {
try {
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
while (!line.equals("Over")) {
try {
line = in.readUTF();
System.out.println(line);
} catch(IOException i) {
System.out.println(i);
}
}
System.out.println("Closing connection");
socket.close();
in.close();
} catch(IOException i) {
System.out.println(i);
}
}
public static void main(String args[]) {
ServerSide server = new ServerSide(5000);
}
}
After configuring both the client and server ends, we can execute the server-side program first.
After that, we have to run the client side program and send the request to server. The server
will reply as soon as the request is sent from the client end. Below are the screenshots of
output.
1. When we run the server-side script, it will start and wait for the client to get started.
Output for server-side code
2. Next, the client will get connected and inputs the request in the form of a string.
Output for client-side code. Then we input a request in string form
3. When the client sends the request, the server will respond back.
Response of server after the request of client
RPC Program to transfer file from client to Server
Server.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static DataOutputStream dataOutputStream = null;
private static DataInputStream dataInputStream = null;
public static void main(String[] args)
{
// Here we define Server Socket running on port 900
try (ServerSocket serverSocket = new ServerSocket(900)) {
System.out.println("Server is Starting in Port 900");
// Accept the Client request using accept method
Socket clientSocket = serverSocket.accept();
System.out.println("Connected");
dataInputStream = new DataInputStream(
clientSocket.getInputStream());
dataOutputStream = new DataOutputStream(
clientSocket.getOutputStream());
// Here we call receiveFile define new for that
// file
receiveFile("C:/Academic/1/VIT Bhopal/Distributed System/NewFile1.pdf");
dataInputStream.close();
dataOutputStream.close();
clientSocket.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
// receive file function is start here
private static void receiveFile(String fileName) throws Exception
{
int bytes = 0;
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
long size = dataInputStream.readLong(); // read file size
byte[] buffer = new byte[4 * 1024];
while (size > 0 && (bytes = dataInputStream.read(buffer, 0,
(int)Math.min(buffer.length, size))) != -1) {
// Here we write the file using write method
fileOutputStream.write(buffer, 0, bytes);
size -= bytes; // read upto file size
}
// Here we received file
System.out.println("File is Received");
fileOutputStream.close();
}
}
Client.java
import java.io.*;
import java.net.Socket;
public class Client {
private static DataOutputStream dataOutputStream = null;
private static DataInputStream dataInputStream = null;
public static void main(String[] args)
{
// Create Client Socket connect to port 900
try (Socket socket = new Socket("localhost", 900)) {
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
System.out.println("Sending the File to the Server");
// Call SendFile Method
sendFile("C:/Academic/1/VIT Bhopal/Distributed System/Chapter1.pdf");
dataInputStream.close();
dataInputStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
// sendFile function define here
private static void sendFile(String path)
throws Exception
{
int bytes = 0;
// Open the File where he located in your pc
File file = new File(path);
FileInputStream fileInputStream = new FileInputStream(file);
// Here we send the File to Server
dataOutputStream.writeLong(file.length());
// Here we break file into chunks
byte[] buffer = new byte[4 * 1024];
while ((bytes = fileInputStream.read(buffer)) != -1) {
// Send the file to Server Socket
dataOutputStream.write(buffer, 0, bytes);
dataOutputStream.flush();
}
// close the file here
fileInputStream.close();
}
}