Rungta College of Engineering and Technology, Bhilai
Department of Computer Science and Engineering
6th SEM Notes
UNIT -2
Socket programming in Java
Socket programming in Java allows different programs to communicate with each other over a
network, whether they are running on the same machine or different ones.
There is a lot of low-level stuff that needs to happen for these things to work but the Java API
networking package ([Link]) takes care of all of that, making network programming very easy for
programmers.
Note: A “socket” is an endpoint for sending and receiving data across a network.
Client-Side Programming
1. Establish a Socket Connection
To connect to another machine we need a socket connection. A socket connection means both
machines know each other’s IP address and TCP port. The [Link] class is used to create
a socket.
Socket socket = new Socket(“[Link]”, 5000)
The first argument: The IP address of Server i.e. [Link] is the IP address of localhost,
where code will run on the single stand-alone machine.
The second argument: The TCP Port numb
er (Just a number representing which application to run on a server. For example, HTTP runs
on port 80. Port number can be from 0 to 65535)
2. Communication
To exchange data over a socket connection, streams are used for input and output:
Input Stream: Reads data coming from the socket.
Output Stream: Sends data through the socket.
Example to access these streams:
// to read data
InputStream input = [Link]();
// to send data
OutputStream output = [Link]();
3. Closing the Connection
The socket connection is closed explicitly once the message to the server is sent.
Example: Here, in the below program the Client keeps reading input from a user and sends it to the
server until “Over” is typed.
// Demonstrating Client-side Programming
import [Link].*;
import [Link].*;
public class Client {
// Initialize socket and input/output streams
private Socket s = null;
private DataInputStream in = null;
private DataOutputStream out = null;
// Constructor to put IP address and port
public Client(String addr, int port)
{
// Establish a connection
try {
s = new Socket(addr, port);
[Link]("Connected");
// Takes input from terminal
in = new DataInputStream([Link]);
// Sends output to the socket
out = new DataOutputStream([Link]());
}
catch (UnknownHostException u) {
[Link](u);
return;
}
catch (IOException i) {
[Link](i);
return;
}
// String to read message from input
String m = "";
// Keep reading until "Over" is input
while () {
try {
m = [Link]();
[Link](m);
}
catch (IOException i) {
[Link](i);
}
}
// Close the connection
try {
[Link]();
[Link]();
[Link]();
}
catch (IOException i) {
[Link](i);
}
}
public static void main(String[] args) {
Client c = new Client("[Link]", 5000);
}
}
Output :
[Link]: Connection refused (Connection refused)
Explanation: In above example, have created a client program that establishes a socket connection to
a server using an IP address and port, enabling data exchange. The client reads messages from the user
and sends them to the server until the message “Over” is entered, after which the connection is closed.
Server-Side Programming
1. Establish a Socket Connection
To create a server application two sockets are needed.
ServerSocket: This socket waits for incoming client requests. It listens for connections on a
specific port.
Socket: Once a connection is established, the server uses this socket to communicate with the
client.
2. Communication
Once the connection is established, you can send and receive data through the socket using
streams.
The getOutputStream() method is used to send data to the client.
3. Close the Connection
Once communication is finished, it’s important to close the socket and the input/output streams to free
up resources.
Example: The below Java program demonstrate the server-side programming
// Demonstrating Server-side Programming
import [Link].*;
import [Link].*;
public class Server {
// Initialize socket and input stream
private Socket s = null;
private ServerSocket ss = null;
private DataInputStream in = null;
// Constructor with port
public Server(int port) {
// Starts server and waits for a connection
try
{
ss = new ServerSocket(port);
[Link]("Server started");
[Link]("Waiting for a client ...");
s = [Link]();
[Link]("Client accepted");
// Takes input from the client socket
in = new DataInputStream(
new BufferedInputStream([Link]()));
String m = "";
// Reads message from client until "Over" is sent
while ()
{
try
{
m = [Link]();
[Link](m);
}
catch(IOException i)
{
[Link](i);
}
}
[Link]("Closing connection");
// Close connection
[Link]();
[Link]();
}
catch(IOException i)
{
[Link](i);
}
}
public static void main(String args[])
{
Server s = new Server(5000);
}
}
Explanation: In the above example, we have implemented a server that listens on a specific port,
accepts a client connection, and reads messages sent by the client. The server displays the messages
until “Over” is received, after which it closes the connection and terminates.
Important Points:
Server application makes a ServerSocket on a specific port which is 5000. This starts our
Server listening for client requests coming in for port 5000.
Then Server makes a new Socket to communicate with the client
socket = [Link]()
The accept() method blocks(just sits there) until a client connects to the server.
Then we take input from the socket using getInputStream() method.
Our Server keeps receiving messages until the Client sends “Over”.
After we’re done we close the connection by closing the socket and the input stream.
To run the Client and Server application on your machine, compile both of them.
Then first run the server application and then run the Client application