Java chat screen

Chat app in java

Ever wanted to make a chat app?

Which only you and your friends know about?

If you ever wanted to do that, you are at right place!¬†Before we start with the chat app, let’s talk a little bit about sockets? If, you are familiar with programming. Then you might have came across this term once or twice.

I know what some of you might be thinking. Why do we need to learn about sockets? Basically, A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to. An endpoint is a combination of an IP address and a port number. With that being said,

 

Let’s get started with the app-

 

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

// class user1 Run this class first and later user2
public class user1 {

    // scanner used to take input from users
    private static Scanner scanner = new Scanner(System.in);

    // main method
    public static void main(String[] args) {

        // calling send method inside main method
        send();

    }

    // send method
    private static void send() {

        // printing server is up
        System.out.println(" Server is up ");

        // calling ServerSocket as serverSocket
        ServerSocket serverSocket;

        String msg = "";

        // assigning post number
        int port = 9999;

        // try and catch method to catch errors
        try {
            // assigning serverSocket port number
            serverSocket = new ServerSocket(port);

            // printing waiting for client
            System.out.println(" waiting for client ");

            // never ending while loop the code below it will execute again and again
            while (true) {

                // calling Socket as s and assigning value of serveSocket by accepting the incoming connection to transfer text to s.
                Socket s = serverSocket.accept();

                // Using buffer reader to read incoming text from socket

                BufferedReader stream = new BufferedReader(new InputStreamReader(s.getInputStream()));

                // Assigning the value of incoming text to String variable msg

                msg = stream.readLine();

                // printing value of msg on the screen

                System.out.println(msg);

                // Taking input from user

                String msgToSend = scanner.nextLine();


                // calling OutputStreamWriter  as os and setting its path to Socket we called as s before

                OutputStreamWriter os = new OutputStreamWriter(s.getOutputStream());

                // calling PrintWriter as send so it can encode the text and send it to socket using OutputStreamWriter

                PrintWriter send = new PrintWriter(os);

                // encoding text and sending it to socket

                send.println(msgToSend);

                // using flush function to make sure the msg is sent

                send.flush();

                // Printing data sent on the screen of user

                System.out.println(" data sent ");

                // closing the connection

                s.close();
            }
        }
        // this part of program will run in case of an error

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

    }
}
// Class user1 ends here

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

// Class user 2

public class user2 {

    // calling Scanner as scanner

    private static Scanner scanner = new Scanner(System.in);

    // main method

    public static void main(String[] args) 
{
        // calling send method in a infinite loop

        while (true)
 {
            send();
        }
    }

    // send method
    private static void send() {

        // calling Socket as socket

        Socket socket;
        // Assigning String ip the value of local host

        String ip = "localhost";
        // Assigning int port value of 9999 which we will use later to connect to other user

        int port = 9999;
        // calling String as msg

        String msg = "";
        // Try and catch block to catch errors

        try {
            // Assigning socket ip and port number on which it is supposed to connect
            socket = new Socket(ip, port);

            // Taking input from user in variable String s
            String s = scanner.nextLine();

            // calling OutputStreamWriter  as outputStreamWriter and setting its path to Socket we called as socket before
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());

            // calling PrintWriter as send so it can encode the text and send it to socket using OutputStreamWriter
            PrintWriter send = new PrintWriter(outputStreamWriter);

            // encoding text and sending it to socket
            send.println(s);

            // using flush function to make sure the msg is sent
            send.flush();

            // Printing msg sent on the screen of user
            System.out.println(" msg sent ");

            // Using buffer reader to read incoming text from socket
            BufferedReader stream = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // Assigning the value of incoming text to String variable msg
            msg = stream.readLine();

            // printing value of msg
            System.out.println(msg);

            // closing socket
            socket.close();

        }
        // this part of program will run in case of an error
        catch (Exception e)
 {
            System.out.println(" Can't send msg");
        }
    }
}
// Class user 2 ends here

If you liked the post Don’t forget to comment and share! And if you have any doubt with code or the functions, then you can comment freely and doubt will be cleared as soon as possible.

2 Comments

  • bryantellez007 says:

    But how it works? i put the class user1 in my java and other PC set the user2? in that way or i’m mistaken?

    • Varmeet says:

      You, need to the change ip in user 2 class , If you are running this on two different computers and make sure that user1 is already running before you run user2.

Leave a Reply