Socket Programming:
Java Networking
• Java networking (or, Java network programming) refers to writing programs that
execute across multiple devices (computers), in which the devices are all
connected to each other using a network.
Advantages of Java Networking
• Creating server-client applications
• Implementing networking protocols
• Implement socket programming
• Creating web services
• Java Socket programming is used for communication between the applications
running on different JRE.
Socket programming is a technique used to establish communication between
two nodes (computers or processes) over a network. It enables data exchange
between a server and a client
Java Socket programming can be connection-oriented or connection-less.
• Sockets provide the communication mechanism between two computers using
TCP. A client program creates a socket on its end of the communication and
attempts to connect that socket to a server.
• When the connection is made, the server creates a socket object on its end of the
communication. The client and the server can now communicate by writing to and
reading from the socket.
• Socket and ServerSocket classes are used for connection-oriented socket
programming and DatagramSocket and DatagramPacket classes are used for
connection-less socket programming.
The client in socket programming must know two information:
1. IP Address of Server, and
2. Port number.
• The Socket class is used to communicate client and server. Through this class, we
can read and write message. The ServerSocket class is used at server-side. After the
successful connection of client, it returns the instance of Socket at server-side.
• The following steps occur when establishing a TCP connection between two
computers using sockets −
• The server instantiates a ServerSocket object, denoting which port
number communication is to occur on.
• The server invokes the accept () method of the ServerSocket class. This
method waits until a client connects to the server on the given port.
• After the server is waiting, a client instantiates a Socket object,
specifying the server’s name and the port number to connect to.
• The constructor of the Socket class attempts to connect the client to the
specified server and the port number. If communication is established,
the client now has a Socket object capable of communicating with the
server.
• On the server side, the accept () method returns a reference to a new
socket on the server that is connected to the client's socket.
After the connections are established, communication can occur using I/O
streams. Each socket has both an OutputStream and an InputStream. The
client's OutputStream is connected to the server's InputStream, and the
client's InputStream is connected to the server's OutputStream.
TCP is a two-way communication protocol; hence data can be sent across both
streams at the same time. Following are the useful classes providing complete
set of methods to implement sockets.
• Socket class
A socket is simply an endpoint for communications between the machines. The
Socket class can be used to create a socket.
Some methods of interest in the Socket class are listed here. Notice that both
the client and the server have a Socket object, so these methods can be
invoked by both the client and the server.
S.No. Method & Description
public void connect (Socket Address host, int
timeout) throws IO Exception
This method connects the socket to the specified
1
host. This method is needed only when you
instantiate the Socket using the no-argument
constructor.
public InetAddress getInetAddress ()
2 This method returns the address of the other
computer that this socket is connected to.
public int getPort ()
3 Returns the port the socket is bound to on the
remote machine.
public int getLocalPort ()
4 Returns the port the socket is bound to on the local
machine.
public SocketAddress getRemoteSocketAddress ()
5
Returns the address of the remote socket.
public InputStream getInputStream () throws
IOException
6 Returns the input stream of the socket. The input
stream is connected to the output stream of the
remote socket.
public OutputStream getOutputStream() throws
IOException
7 Returns the output stream of the socket. The output
stream is connected to the input stream of the
remote socket.
public void close () throws IOException
8 Closes the socket, which makes this Socket object no
longer capable of connecting again to any server.
• ServerSocket class
The ServerSocket class can be used to create a server socket. This object is
used to establish communication with the clients.
ServerSocket Class Methods
Following is some of the common methods of the ServerSocket class −
S.No. Method & Description
public int getLocalPort ()
Returns the port that the server socket is listening on.
1 This method is useful if you passed in 0 as the port
number in a constructor and let the server find a port
for you.
public Socket accept () throws IOException
Waits for an incoming client. This method blocks until
2 either a client connects to the server on the specified
port or the socket times out, assuming that the time-
out value has been set using the setSoTimeout()
method. Otherwise, this method blocks indefinitely.
public void setSoTimeout (int timeout)
3 Sets the time-out value for how long the server
socket waits for a client during the accept().
public void bind (SocketAddress host, int backlog)
Binds the socket to the specified server and port in
4 the SocketAddress object. Use this method if you
have instantiated the ServerSocket using the no-
argument constructor.
When the ServerSocket invokes accept (), the method does not return until a
client connects. After a client does connect, the ServerSocket creates a new
Socket on an unspecified port and returns a reference to this new Socket. A
TCP connection now exists between the client and the server, and
communication can begin.
• We’ll create a basic client-server communication where the client sends a message
to the server, and the server reads and prints it.
Server Side:
1. Creating the Server:
o We need to create an instance of the ServerSocket class.
o In this example, we’ll use port number 6666 for communication
between the client and server. You can choose any other port
number.
o The accept () method waits for the client. When a client connects
with the given port number, it returns an instance of Socket.
Java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(6666);
Socket s = ss.accept(); // Establishes connection and waits for
the client
DataInputStream dis = new
DataInputStream(s.getInputStream());
String message = dis.readUTF(); // Read the message from the
client
System.out.println("Received message from client: " + message);
ss.close(); // Close the server socket
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client Side:
1. Creating the Client:
o We need to create an instance of the Socket class.
o Pass the IP address or hostname of the server and the port
number.
o In this example, we’re using "localhost" because our server is
running on the same system.
Java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 6666); // Connect to the
server
DataOutputStream dos = new
DataOutputStream(s.getOutputStream());
String message = "Hello from client!";
dos.writeUTF(message); // Send the message to the server
s.close(); // Close the client socket
} catch (IOException e) {
e.printStackTrace();
}
}
}