A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.
Launch Xperto-AIHey there, fellow Java enthusiasts! Today, we're going to embark on an exciting journey to build a basic chat application using Java. Whether you're a beginner looking to dip your toes into network programming or an intermediate developer wanting to brush up on your skills, this tutorial is perfect for you. So, grab your favorite beverage, fire up your IDE, and let's get started!
Before we dive into the code, let's quickly go over the fundamental concepts we'll be working with:
Now that we have our bearings, let's break down our application into manageable chunks.
First things first, we need to create our server. This will be the central hub that all our clients connect to. Here's a basic implementation:
import java.io.*; import java.net.*; import java.util.*; public class ChatServer { private static final int PORT = 9001; private static HashSet<PrintWriter> writers = new HashSet<>(); public static void main(String[] args) throws Exception { System.out.println("The chat server is running..."); ServerSocket listener = new ServerSocket(PORT); try { while (true) { new Handler(listener.accept()).start(); } } finally { listener.close(); } } private static class Handler extends Thread { private Socket socket; private PrintWriter out; private BufferedReader in; public Handler(Socket socket) { this.socket = socket; } public void run() { try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); writers.add(out); while (true) { String input = in.readLine(); if (input == null) { return; } for (PrintWriter writer : writers) { writer.println("Message: " + input); } } } catch (IOException e) { System.out.println(e); } finally { if (out != null) { writers.remove(out); } try { socket.close(); } catch (IOException e) { } } } } }
This server listens for incoming connections on port 9001. When a client connects, it creates a new Handler
thread to manage that connection. The Handler
class reads messages from the client and broadcasts them to all connected clients.
Now that we have our server up and running, let's create the client side of our chat application. We'll use Swing to create a simple GUI:
import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import javax.swing.*; public class ChatClient { private BufferedReader in; private PrintWriter out; private JFrame frame = new JFrame("Chatter"); private JTextField textField = new JTextField(40); private JTextArea messageArea = new JTextArea(8, 40); public ChatClient() { textField.setEditable(false); messageArea.setEditable(false); frame.getContentPane().add(textField, "North"); frame.getContentPane().add(new JScrollPane(messageArea), "Center"); frame.pack(); textField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { out.println(textField.getText()); textField.setText(""); } }); } private void run() throws IOException { String serverAddress = JOptionPane.showInputDialog( frame, "Enter IP Address of the Server:", "Welcome to the Chatter", JOptionPane.QUESTION_MESSAGE); Socket socket = new Socket(serverAddress, 9001); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); while (true) { String line = in.readLine(); if (line.startsWith("SUBMITNAME")) { out.println(getName()); } else if (line.startsWith("NAMEACCEPTED")) { textField.setEditable(true); } else if (line.startsWith("Message")) { messageArea.append(line.substring(8) + "\n"); } } } private String getName() { return JOptionPane.showInputDialog( frame, "Choose a screen name:", "Screen name selection", JOptionPane.PLAIN_MESSAGE); } public static void main(String[] args) throws Exception { ChatClient client = new ChatClient(); client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); client.frame.setVisible(true); client.run(); } }
This client creates a simple GUI with a text field for entering messages and a text area for displaying the chat history. It connects to the server, prompts the user for a name, and then allows them to send and receive messages.
Now that we have both our server and client code, let's test our chat application:
ChatServer
class.ChatClient
class.Great job! We now have a basic chat application up and running. But why stop here? There are many ways we can improve and expand our project:
As you continue to develop your chat application, keep these points in mind:
Remember, building a chat application is an iterative process. Start with the basics, test thoroughly, and gradually add more features as you become more comfortable with the concepts.
I hope this tutorial has given you a solid foundation for creating your own chat application in Java. Happy coding, and don't forget to have fun along the way!
03/11/2024 | System Design
15/11/2024 | System Design
15/09/2024 | System Design
02/10/2024 | System Design
06/11/2024 | System Design
02/10/2024 | System Design
02/10/2024 | System Design
02/10/2024 | System Design
02/10/2024 | System Design
02/10/2024 | System Design