Java Socket Programming allows communication between two nodes (computers) over a network. It enables the creation of client-server applications where the client and server can exchange data in real-time.
Here are the basic steps involved in Java Socket Programming:
- Create a ServerSocket object on the server-side with a specified port number to listen for incoming requests.
- Use the accept() method of ServerSocket to block and wait for incoming client requests.
- Create a Socket object on the client-side, specifying the server IP address and port number to connect to.
- Use the getInputStream() and getOutputStream() methods of the Socket class to establish a two-way communication channel between the client and server.
- Send and receive data between the client and server using the streams.
- Close the Socket and ServerSocket objects after the communication is completed.
Here is a simple Java code example for a basic client-server communication:
Server Side
import java.net.*; import java.io.*; public class Server { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(5000); } catch (IOException e) { System.err.println("Could not listen on port: 5000."); System.exit(1); } Socket clientSocket = null; try { System.out.println("Waiting for client connection..."); clientSocket = serverSocket.accept(); System.out.println("Client connected: " + clientSocket.getInetAddress().getHostName()); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println("Client: " + inputLine); out.println(inputLine); if (inputLine.equals("Bye.")) break; } out.close(); in.close(); clientSocket.close(); serverSocket.close(); } }
Client Side
import java.net.*; import java.io.*; public class Client { public static void main(String[] args) throws IOException { Socket socket = null; PrintWriter out = null; BufferedReader in = null; try { socket = new Socket("localhost", 5000); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Unknown host: localhost"); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: localhost."); System.exit(1); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("Server: " + in.readLine()); if (userInput.equals("Bye.")) break; } out.close(); in.close(); stdIn.close(); socket.close(); } }
In this example, the client connects to the server on localhost port 5000. The client sends messages to the server, and the server echoes back the same message to the client. The communication continues until either the client or server sends the message “Bye.”, which ends the communication.
Socket class:
The Socket
class in Java is a fundamental class in socket programming that enables communication between two nodes over a network. It represents a client-side socket that establishes a connection to a server-side socket.
The Socket
class provides methods for creating, connecting, sending, and receiving data over a network. Here are some of the commonly used methods in the Socket
class:
Socket(String host, int port)
: This constructor creates a newSocket
object and connects it to the specified host and port number.void close()
: This method closes the socket connection.InputStream getInputStream()
: This method returns the input stream of this socket.OutputStream getOutputStream()
: This method returns the output stream of this socket.InetAddress getInetAddress()
: This method returns the IP address of the remote host to which this socket is connected.int getPort()
: This method returns the remote port number to which this socket is connected.boolean isConnected()
: This method returnstrue
if the socket is connected to a remote host.
Here is an example of how to use the Socket
class to connect to a server and send data:
import java.io.*; import java.net.*; public class Client { public static void main(String[] args) throws IOException { Socket socket = null; PrintWriter out = null; BufferedReader in = null; try { socket = new Socket("localhost", 5000); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Unknown host: localhost"); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: localhost."); System.exit(1); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("Server: " + in.readLine()); if (userInput.equals("Bye.")) break; } out.close(); in.close(); stdIn.close(); socket.close(); } }
In this example, a Socket
object is created and connected to the server at “localhost” on port 5000. The getOutputStream()
method is used to obtain an output stream to send data to the server, and the getInputStream()
method is used to obtain an input stream to receive data from the server. The close()
method is used to close the socket connection after the communication is completed.
Important methods:
Here are some important methods in the Socket
class in Java:
Socket(String host, int port)
: This constructor creates a newSocket
object and connects it to the specified host and port number.void close()
: This method closes the socket connection.InputStream getInputStream()
: This method returns the input stream of this socket.OutputStream getOutputStream()
: This method returns the output stream of this socket.InetAddress getInetAddress()
: This method returns the IP address of the remote host to which this socket is connected.int getPort()
: This method returns the remote port number to which this socket is connected.boolean isConnected()
: This method returnstrue
if the socket is connected to a remote host.void setSoTimeout(int timeout)
: This method sets the timeout value in milliseconds for blocking socket operations.void setKeepAlive(boolean on)
: This method enables or disables theSO_KEEPALIVE
socket option.void setTcpNoDelay(boolean on)
: This method enables or disables theTCP_NODELAY
socket option.void setReuseAddress(boolean on)
: This method enables or disables theSO_REUSEADDR
socket option.void setReceiveBufferSize(int size)
: This method sets the size of the receive buffer for this socket.void setSendBufferSize(int size)
: This method sets the size of the send buffer for this socket.int getReceiveBufferSize()
: This method returns the size of the receive buffer for this socket.int getSendBufferSize()
: This method returns the size of the send buffer for this socket.
These methods provide various options for configuring and managing socket connections in Java.
ServerSocket class:
The ServerSocket
class in Java is used to create a server-side socket that listens for incoming client connections. It is the counterpart to the Socket
class and is used to accept connections from client sockets.
Here are some of the commonly used methods in the ServerSocket
class:
ServerSocket(int port)
: This constructor creates a newServerSocket
object that is bound to the specified port number.Socket accept()
: This method listens for a connection to be made to this socket and accepts it.void close()
: This method closes the server socket.int getLocalPort()
: This method returns the port number to which this socket is bound.InetAddress getInetAddress()
: This method returns the IP address of the local host to which this socket is bound.boolean isBound()
: This method returnstrue
if the server socket is bound to a port.boolean isClosed()
: This method returnstrue
if the server socket is closed.
Here is an example of how to use the ServerSocket
class to create a server that listens for client connections:
import java.io.*; import java.net.*; public class Server { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(5000); } catch (IOException e) { System.err.println("Could not listen on port: 5000."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println("Client: " + inputLine); out.println(inputLine); if (inputLine.equals("Bye.")) break; } out.close(); in.close(); clientSocket.close(); serverSocket.close(); } }
In this example, a ServerSocket
object is created and bound to port 5000. The accept()
method is used to listen for a client connection and accept it. The getOutputStream()
method is used to obtain an output stream to send data to the client, and the getInputStream()
method is used to obtain an input stream to receive data from the client. The close()
method is used to close the socket connection after the communication is completed.
Important methods:
Here are some of the commonly used methods in the ServerSocket
class:
ServerSocket(int port)
: This constructor creates a newServerSocket
object that is bound to the specified port number.Socket accept()
: This method listens for a connection to be made to this socket and accepts it.void close()
: This method closes the server socket.int getLocalPort()
: This method returns the port number to which this socket is bound.InetAddress getInetAddress()
: This method returns the IP address of the local host to which this socket is bound.boolean isBound()
: This method returnstrue
if the server socket is bound to a port.boolean isClosed()
: This method returnstrue
if the server socket is closed.
These methods provide various options for configuring and managing the server-side socket connections in Java.
Example of Java Socket Programming:
Sure, here’s an example of a simple client-server application in Java using socket programming:
Server Side
import java.io.*; import java.net.*; public class Server { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(5000); } catch (IOException e) { System.err.println("Could not listen on port: 5000."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println("Client: " + inputLine); out.println(inputLine); if (inputLine.equals("Bye.")) break; } out.close(); in.close(); clientSocket.close(); serverSocket.close(); } }
Client Side
import java.io.*; import java.net.*; public class Client { public static void main(String[] args) throws IOException { Socket socket = null; PrintWriter out = null; BufferedReader in = null; try { socket = new Socket("localhost", 5000); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: localhost."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: localhost."); System.exit(1); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("Server: " + in.readLine()); if (userInput.equals("Bye.")) break; } out.close(); in.close(); stdIn.close(); socket.close(); } }
In this example, the server is listening on port 5000 for incoming client connections. When a client connects, the server reads the input from the client and sends the same data back to the client. On the client side, the client connects to the server and sends user input to the server. The client then reads the server’s response and displays it to the user.
Note: In this example, we’re creating a blocking socket, meaning that when one side of the connection is sending data, the other side is blocked from doing anything else until the data is fully received. It’s possible to implement non-blocking sockets as well, which can improve performance for certain applications.
Example of Java Socket Programming (Read-Write both side):
Sure, here’s an example of a Java Socket Programming code that allows for read-write operations on both the client and server sides:
Server Side
import java.io.*; import java.net.*; public class Server { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(5000); } catch (IOException e) { System.err.println("Could not listen on port: 5000."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); System.out.println("Client connected."); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } out.close(); in.close(); stdIn.close(); clientSocket.close(); serverSocket.close(); } }
Client Side
import java.io.*; import java.net.*; public class Client { public static void main(String[] args) throws IOException { Socket socket = null; PrintWriter out = null; BufferedReader in = null; try { socket = new Socket("localhost", 5000); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println("Connected to server."); } catch (UnknownHostException e) { System.err.println("Don't know about host: localhost."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: localhost."); System.exit(1); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } out.close(); in.close(); stdIn.close(); socket.close(); } }
In this example, both the server and the client sides can read and write to the socket connection. The server waits for a client to connect, and then reads input from the client and sends the same data back to the client. On the client side, the client connects to the server and reads input from the user, then sends that input to the server and displays the server’s response to the user.
Note: This example also uses a blocking socket. It’s possible to use non-blocking sockets as well, which can improve performance for certain applications.