Java Client

On the Java client side, we will pass the two most important information to the Socket class. This information connects the Java Client Socket to the Java Server Socket.

  • IP Address of Server and,
  • Port Number

In the Java client, we create a new thread when each new message is received from the Java Server Client.

Java




import java.io.*;
import java.net.*;
import java.util.Scanner;
  
public class Client {
    private static final String SERVER_ADDRESS = "localhost";
    private static final int SERVER_PORT = 12345;
  
    public static void main(String[] args) {
        try {
            Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
            System.out.println("Connected to the chat server!");
  
            // Setting up input and output streams
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  
            // Start a thread to handle incoming messages
            new Thread(() -> {
                try {
                    String serverResponse;
                    while ((serverResponse = in.readLine()) != null) {
                        System.out.println(serverResponse);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
  
            // Read messages from the console and send to the server
            Scanner scanner = new Scanner(System.in);
            String userInput;
            while (true) {
                userInput = scanner.nextLine();
                out.println(userInput);
            }
             
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


How to Implement a Simple Chat Application Using Sockets in Java?

In this article, we will create a simple chat application using Java socket programming. Before we are going to discuss our topic, we must know Socket in Java. Java Socket connects two different JREs (Java Runtime Environment).

  • Java sockets can be connection-oriented or connection-less.
  • In Java, we have the java.net package.
  • Java Socket can be connectionless or connection-oriented.

Similar Reads

Java Client

On the Java client side, we will pass the two most important information to the Socket class. This information connects the Java Client Socket to the Java Server Socket....

Java Server

...