The Wayback Machine - https://web.archive.org/web/20240910090940/https://www.geeksforgeeks.org/a-group-chat-application-in-java/
Open In App

A Group chat application in Java

Last Updated : 28 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this post, a group chat application using MulticastSocket (Java Platform SE 7) class is discussed. A MulticastSocket is a (UDP) DatagramSocket, with additional capabilities for joining “groups” of other multicast hosts on the internet.

Implementation




import java.net.*;
import java.io.*;
import java.util.*;
public class GroupChat
{
    private static final String TERMINATE = "Exit";
    static String name;
    static volatile boolean finished = false;
    public static void main(String[] args)
    {
        if (args.length != 2)
            System.out.println("Two arguments required: <multicast-host> <port-number>");
        else
        {
            try
            {
                InetAddress group = InetAddress.getByName(args[0]);
                int port = Integer.parseInt(args[1]);
                Scanner sc = new Scanner(System.in);
                System.out.print("Enter your name: ");
                name = sc.nextLine();
                MulticastSocket socket = new MulticastSocket(port);
              
                // Since we are deploying
                socket.setTimeToLive(0);
                //this on localhost only (For a subnet set it as 1)
                  
                socket.joinGroup(group);
                Thread t = new Thread(new
                ReadThread(socket,group,port));
              
                // Spawn a thread for reading messages
                t.start(); 
                  
                // sent to the current group
                System.out.println("Start typing messages...\n");
                while(true)
                {
                    String message;
                    message = sc.nextLine();
                    if(message.equalsIgnoreCase(GroupChat.TERMINATE))
                    {
                        finished = true;
                        socket.leaveGroup(group);
                        socket.close();
                        break;
                    }
                    message = name + ": " + message;
                    byte[] buffer = message.getBytes();
                    DatagramPacket datagram = new
                    DatagramPacket(buffer,buffer.length,group,port);
                    socket.send(datagram);
                }
            }
            catch(SocketException se)
            {
                System.out.println("Error creating socket");
                se.printStackTrace();
            }
            catch(IOException ie)
            {
                System.out.println("Error reading/writing from/to socket");
                ie.printStackTrace();
            }
        }
    }
}
class ReadThread implements Runnable
{
    private MulticastSocket socket;
    private InetAddress group;
    private int port;
    private static final int MAX_LEN = 1000;
    ReadThread(MulticastSocket socket,InetAddress group,int port)
    {
        this.socket = socket;
        this.group = group;
        this.port = port;
    }
      
    @Override
    public void run()
    {
        while(!GroupChat.finished)
        {
                byte[] buffer = new byte[ReadThread.MAX_LEN];
                DatagramPacket datagram = new
                DatagramPacket(buffer,buffer.length,group,port);
                String message;
            try
            {
                socket.receive(datagram);
                message = new
                String(buffer,0,datagram.getLength(),"UTF-8");
                if(!message.startsWith(GroupChat.name))
                    System.out.println(message);
            }
            catch(IOException e)
            {
                System.out.println("Socket closed!");
            }
        }
    }
}


Save the file as GroupChat.java and compile it using javac and then run the program using two command line arguments as specified. A multicast host is specified by a class D IP address and by a standard UDP port number. Class D IP addresses are in the range 224.0.0.0 to 239.255.255.255, inclusive. The address 224.0.0.0 is reserved and should not be used.
Here is a sample output of the above program:
multicast socket api in java

multicast socket api in java1multicast socket api in java12
We have used the multicast host IP address as 239.0.0.0 and the port number as 1234 (since the port numbers 0 through 1023 are reserved). There are 3 members in the group: Ironman, CaptainAmerica, and Groot. Start all three terminals first before sending the message, otherwise messages which are sent before starting the terminal are lost (since there is no facility of buffer incorporated to store the messages.) We need two threads in this application. One for accepting the user input (using the java.util.Scanner class) and the other for reading the messages sent from other clients. Hence I have separated the thread which does the reading work into ReadThreadclass. For leaving the group, any of the user can type in Exit to terminate the session.

The above program is executed on a single machine. Socket programming is meant for distributed programming. The same piece of code snippet when present on different machines which have Java installed can satisfy that requirement. This is just the bare bones service logic. The project would be even more fascinating if the front-end is developed. You can use Java’s AWT (Abstract Window Toolkit) or its advanced counterpart, Java Swing to develop the front end. Since this wouldn’t be part of Socket programming I’m leaving it untouched without getting into the details.
Additional points:

  • You can incorporate network security feature by performing encryption before sending the message over the network.
  • Primitive techniques such as Caesar cipher or advanced methods such as RSA can be used to perform encryption-decryption. You can try using Java’s RMI (Remote Method Invocation) to perform the same task.
  • Here, you can leverage the abstraction offered by Java to maximum extent. However, if your primary objective is efficiency, then Socket programming is the best choice. Since it doesn’t require any run time support, it is a bit faster compared to RMI.


Similar Reads

Multi-threaded chat Application in Java | Set 1 (Server Side Programming)
Prerequisites : Introducing threads in socket programmingIn the above article, a simple date time server was created which handled multiple user requests at the same time using threading. It explains the basic concepts of threading in network programming. The same concepts can be used with very slight modification to extend the above idea and creat
5 min read
Multi-threaded Chat Application in Java | Set 2 (Client Side Programming)
Prerequisites : Introducing threads in socket programming, Multi-threaded chat Application | Set 1 This article gives the implementation of client program for the multi-threaded chat application. Till now all examples in socket programming assume that client first sends some information and then server or other clients responds to that information.
5 min read
GUI chat application using Tkinter in Python
Chatbots are computer program that allows user to interact using input methods. The Application of chatbots is to interact with customers in big enterprises or companies and resolve their queries. Chatbots are mainly built for answering standard FAQs. The benefit of this type of system is that customer is no longer required to follow the same tradi
7 min read
Real-time chat application in JavaScript
A real-time chat application is a software application that enables users to exchange messages and communicate with each other in real-time. It allows individuals or groups to have conversations, share information, and collaborate instantly over the Internet. Real-time chat applications are designed to provide a responsive and interactive experienc
7 min read
Create a Chat App with Vue.js
In this article, we will explore how to build a real-time chat application using Socket.IO and Vue.js. Socket.IO is a popular library that enables real-time, bidirectional, and event-based communication between the client and the server. By integrating Socket.IO with Vue.js, we can create a seamless and interactive chat experience for users. Prereq
4 min read
How to Implement Chat Functionality in Social Media Android App?
This is the Part 14 of "Build a Social Media App on Android Studio" tutorial, and we are going to cover the following functionalities in this article: We are going to Create a Layout for chat &amp; Send Messages in Chat.A user can send either a Message or an Image.A user can send an image either using a camera or gallery.Firstly a request for permi
15+ min read
Chat Website using MERN Stack
The "Chat Website" project is a dynamic web application that is used for real-time communication. The MERN stack, comprised of MongoDB, Express.js, React.js, and Node.js, is a powerful combination of technologies for developing robust and scalable web applications. In this article, we'll explore the process of building a real-time chat website usin
4 min read
Spring Boot - application.yml/application.yaml File
Spring is widely used for creating scalable applications. For web applications Spring provides. In Spring Boot, whenever we create a new Spring Boot Application in spring starter, or inside an IDE (Eclipse or STS) a file is located inside the src/main/resources folder named as application.properties file which is shown in the below media: So in a s
4 min read
Difference between a Java Application and a Java Applet
Java Application is just like a Java program that runs on an underlying operating system with the support of a virtual machine. It is also known as an application program. The graphical user interface is not necessary to execute the java applications, it can be run with or without it. Java Applet is a Java program that can be embedded into a web pa
3 min read
Matcher group() method in Java with Examples
The group() method of Matcher Class is used to get the input subsequence matched by the previous match result. Syntax: public String group() Parameters: This method do not takes any parameter. Return Value: This method returns the String which is the input subsequence matched by the previous match. Exception: This method throws IllegalStateExceptio
2 min read
Matcher group(String) method in Java with Examples
The group(String string) method of Matcher Class is used to get the group of the match result already done, from the specified string. Syntax: public String group(String string) Parameters: This method takes a parameter string which is the String from which the group index of the matched pattern is required. Return Value: This method returns the gr
2 min read
Matcher group(int) method in Java with Examples
The group(int group) method of Matcher Class is used to get the group index of the match result already done, from the specified group. Syntax: public String group(int group) Parameters: This method takes a parameter group which is the group from which the group index of the matched pattern is required. Return Value: This method returns the index o
2 min read
MatchResult group() method in Java with Examples
The group() method of MatchResult Interface is used to get the input subsequence matched by the previous match result.Syntax: public String group() Parameters: This method do not takes any parameter.Return Value: This method returns the String which is the input subsequence matched by the previous match.Exception: This method throws IllegalStateExc
2 min read
MatchResult group(int) method in Java with Examples
The group(int group) method of MatchResult Interface is used to get the group index of the match result already done, from the specified group. Syntax: public String group(int group) Parameters: This method takes a parameter group which is the group from which the group index of the matched pattern is required. Return Value: This method returns the
2 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Creating First Java Application in IntelliJ IDEA
IntelliJ IDEA is a Java IDE that is one of the 3 biggest and most popular IDE’s in the world. It has two versions, namely the free open-source community edition and a paid Ultimate edition. Some features of IntelliJ IDEA are as follows: Both versions of IntelliJ IDEA support various programming languages like Java, Scala, Kotlin, Groovy, etc.There
4 min read
How to run Java RMI Application
Prerequisite: RMI RMI (Remote Method Invocation) is used for distributed object references system. A distributed object is an object which publishes its interface on other machines. A Remote Object is a distributed object whose state is encapsulated. Stub and Skeleton are two objects used to communicate with the remote object. Stub: Stub is a gatew
4 min read
Implementation of CI/CD in Java application(Linux) Using Shell and Docker Executor on GitLab
There are many executors available to implement CI/CD with GitLab Runner. However, Shell and Docker are more popular among them, and we can easily configure a repository with these runners. These runners can be chosen based on the requirements and availability of the resources. This article mainly focuses on Shell and Docker executors of Java Linux
6 min read
How to Setup GSON For Java Application?
GSON is Google's JSON parser. It is used to parse JSON files and generate JSON files. It has multiple APIs which serialize Java objects to JSON and deserializes JSON files to Java objects. To use GSON in your java application, we first need to install it. To do this, we can either add GSON jar dependency in Maven pom.xml file or we can download the
7 min read
Standard Practice For Protecting Sensitive Data in Java Application
We can use encryption techniques to save our data. Encryption is the method by which information is converted into secret code that hides the information's true meaning. The science of encrypting and decrypting information is called cryptography. In computing, unencrypted data is also known as plaintext, and encrypted data is called ciphertext. The
6 min read
How to Install Boon and Configuring it with Java Application?
Boon is a tool based on java used to efficiently encode or decode JSON in a fast way. Boon is a less known Java JSON API, Boon is also being used as the standard JSON API in Groovy. Boon is one of the general-purpose toolkits for working with data easily. Boon contains ObjectMapper which can parse JSON into custom objects or Java Maps. We can use t
4 min read
How to Setup Jackson in Java Application?
JSON(Javascript Object Notation) is the most popular format for the exchange of data in the world of web applications. The browsers can easily parse json requests and convert them to javascript objects. The servers parse json requests, process them, and generates a new json response. JSON is self-describing and easy to understand. The process of co
7 min read
Java Application to Implement Bank Functionality
The java program developed here is to implement bank functionality. The user can create an account, check, deposit money, withdraw, and also search account. At first, we created an interface called the central bank to do a few operations mentioned above. Then we created three subclass UNB, FGB, and NBD these classes will take customer account detai
6 min read
How to Write Test Cases in Java Application using Mockito and Junit?
Mockito is an open-source testing framework used for unit testing of Java applications. It plays a vital role in developing testable applications. Mockito is used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in Unit Testing. Unit Testing is a type of software testing in which individual componen
4 min read
How to Generate Code Coverage Report with JaCoCo in Java Application?
Testing is a most important part of a software development lifecycle. Without testing, the software is not ready for deployment. To test Java applications we mostly used Junit. JUnit framework is a Java framework that is used for testing. And now, JUnit is used as a standard when there is a need to perform testing in Java. But what is Code Coverage
4 min read
Deadlock in Single Threaded Java Application
Deadlock describes a situation where two or more threads are blocked forever because they are waiting for each other. There are many causes of deadlocks. Two or more threads can deadlock when the following conditions hold: Threads that are already holding locks request for new locks.The requests for new locks are made concurrently by the threads.Tw
3 min read
How to Enable JMX For Java Application Running in the Kubernetes Cluster?
Many times we want to monitor our application's CPU utilization, background thread behavior, and most importantly memory consumptions for tasks that deal with loads for data (500MB - 1GB) or much more data. Such monitoring helps to find which operation is causing heavy CPU or Memory utilization and helps to find the reason behind Memory leak issues
3 min read
Enable Remote Debugging For Java Application Deployed in Kubernetes Environment
During Development, developers have to debug their applications to resolve code problems. In order to debug a java application which is deployed on remote machine in a Kubernetes cluster, first developer has to do some steps to enable its application ready for debugging. Below are the manual steps to enable remote debugging for any java application
2 min read
Create a Simple Login Web Application with Encrypted Password in Java
Security is an important concept in any web application. We need to have the passwords stored in an encrypted way i.e. the passwords are not easily accessible by hackers or unauthorized users. Let's see a small demo application in this article using MySQL, Java, Servlet, and JSP technology. Step by Step Implementation Required MySQL Script -- Here
10 min read
How to Test Java Application using TestNG?
TestNG is an automation testing framework widely getting used across many projects. NG means “Next Generation” and it is influenced by JUnit and it follows the annotations (@). End-to-end testing is easily handled by TestNG. As a sample, let us see the testing as well as the necessity to do it via a maven project. Sample Maven Project Project Struc
4 min read
Article Tags :
Practice Tags :