Sockets programming in Java

Socket programming is a way of creating communication between two or more applications running on a network. It allows applications to exchange data with each other in a reliable and efficient manner.

What is socket in computer programming?

A socket is a endpoint of a two-way communication link between two programs running on a network. It is a common interface for network communication, allowing programs to send and receive data over a network connection using standard communication protocols such as TCP and UDP. Sockets are used in various types of networked applications, including web servers, database servers, and game servers, to establish communication between different parts of the application.

What is server side socket programming?

Server-side socket programming refers to the implementation of network communication protocols on the server side, using socket APIs, to enable communication between the server and clients. It involves creating a socket on the server side, binding it to a specific port, and listening for incoming connections from clients. When a connection is established, the server can receive and send data to the client. This type of socket programming is commonly used for building network-based applications such as web servers, game servers, and other networked services.

What is client side socket programming?

Client-side socket programming refers to the implementation of network communication protocols on the client side, using socket APIs, to enable communication between the client and server. It involves creating a socket on the client side and connecting it to a server using a specific IP address and port number. The client can then send data to the server and receive data from it. This type of socket programming is commonly used for building client applications that connect to networked services such as web servers, game servers, and other networked services.

How to Socket programming in java?


How to Java TCP/IP UDP socket programming
To implement socket programming in Java, you can use the java.net package, which provides a set of classes and methods for creating and using sockets. Here are the steps to implement a basic socket program in Java:

How to create a Java Server Socket Program

  1. Create a server socket on the server side using the ServerSocket class, passing in the desired port number as an argument.
  2. Listen for incoming connections on the server side using the accept method, which returns a Socket object for the new connection.
  3. Create an input stream on the server side using the getInputStream method, and read data from the client using the read method.
  4. Create an output stream on the server side using the getOutputStream method, and write data to the client using the write method.
  5. Close the sockets on both the client and server sides using the close method.

Java Server side Socket Programming Example

import java.io.*; import java.net.*; public class MyServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(10007); } catch (IOException e) { System.err.println("Could not listen on port: 10007."); 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) { out.println("From Server ->> " + inputLine); } out.close(); in.close(); clientSocket.close(); serverSocket.close(); } }

How to create a Java Client Socket Program

  1. Create a socket on the client side using the Socket class, passing in the server's IP address and port number as arguments.
  2. Create an output stream on the client side using the getOutputStream method, and write data to the server using the write method.
  3. Create an input stream on the client side using the getInputStream method, and read data from the server using the read method.

Java Client side Socket Programming Example

import java.io.*; import java.net.*; public class MyClient { public static void main(String[] args) throws IOException { Socket mySocket = null; PrintWriter out = null; BufferedReader in = null; try { mySocket = new Socket("localhost", 10007); out = new PrintWriter(mySocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(mySocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: localhost."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't getin 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(in.readLine()); } out.close(); in.close(); stdIn.close(); mySocket.close(); } }
In the above example, the client creates a socket and connects to a server running on the same machine (localhost) at port 10007. It then creates an output stream and a buffered reader to write data to the server and receive data from it, respectively. The client prompts the user for input, writes the input to the server, and prints the server's response to the screen. Finally, it closes all the streams and the socket when the user enters null.

How to run the server and client socket program in java

To run the server-side and client-side socket programs in Java, you need to have the Java Development Kit (JDK) installed on your machine. You can then compile the code using the javac command and run the compiled code using the java command.

Steps to run the server-side socket program:

  1. Open a terminal/command prompt window.
  2. Change the current directory to the location where the server-side code is saved.
  3. Compile the Java source code using the following command:
javac MyServer.java
  1. Run the compiled Java code using the following command:
java MyServer
The server will start listening on the specified port for incoming connections.

Steps to run the client-side socket program:

  1. Open a second terminal or command prompt window.
  2. Change the current directory to the location where the client-side code is saved.
  3. Compile the code using the following command:
javac MyClient.java
  1. Run the compiled Java code using the following command:
java MyClient
The client will connect to the server, and you will be able to send messages to the server and receive responses from it. Note: Make sure that the server is running and accessible before you run the client. Also, you can run the server and client on different machines if they are connected to the same network. In this case, you will need to use the IP address of the server machine instead of localhost in the client code.