Java Client-Server Connection with Code Examples

 Here's a revised and optimized version of your blog post content:


Java Client-Server Connection:

Server Side Java Code: (EchoServer.java)

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoServer {
    public static void main(String[] args) {
        
        try {
            System.out.println("Waiting for clients...");
            ServerSocket serverSocket = new ServerSocket(9806);
            Socket socket = serverSocket.accept();
            System.out.println("Connection established.");

            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String message = input.readLine();
            System.out.println("Client says: " + message);

            PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
            output.println("Server says: " + message);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Client Side Java Code: (EchoClient.java)

import java.io.*;
import java.net.Socket;

public class EchoClient {
    public static void main(String[] args) {
        
        try {
            System.out.println("Client started");

            Socket socket = new Socket("localhost", 9806);
            BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter a string:");
            String message = userInput.readLine();

            PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
            output.println(message);

            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println(input.readLine());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation of Code:

Server Side Explanation:

  • The EchoServer listens on port 9806 for incoming connections using a ServerSocket.
  • Once a client connects, the server creates a socket for that connection.
  • Data is received via the input stream and echoed back via the output stream.

Client Side Explanation:

  • The EchoClient connects to localhost on port 9806.
  • The client sends a message to the server through the output stream and waits for the server's response via the input stream.

Key Points:

  • Always ensure the server code is running first before starting the client.
  • Both client and server use streams (input and output) to send and receive data.
  • A socket is used to establish the connection between the client and server.


Post a Comment (0)
Previous Post Next Post