[Java × Socket communication] Create your own real-time chat app! Includes code explanations that even beginners can use.

programming

"I want to learn real-time communication in Java, but it seems difficult."
"I want to be able to create two-way communication like in a chat app."
If you have such concerns,Experience building a simple chat app using Javais.

If you use socket communication,Realizing one-to-one communication in real timecan.
Starting with a simple structure,Network communication mechanisms and error handlingYou will naturally acquire this skill.

In this article,A chat app that even beginners can createof,
We will explain it from a professional perspective in an easy-to-understand manner and include code.


What is a chat app?

This is the best subject for learning real-time communication.

Conclusion: Creating a chat app will help you learn the basics of network communication.

Java has Socket There is a communication mechanism in place,
This allows programs toSend and receive messagescan.

Real-time communication is used in a wide range of fields, including LINE and games.
Creating this system yourself and experiencing it will directly improve your practical skills.


Configuration and required functions

At least two programs are required

In conclusion: create a server side and a client side.

The configuration is as follows:

1
src/ ├─ ChatServer.java └─ ChatClient.java

Functions achieved:

  • Client sends a message
  • The server receives the message and relays it to everyone
  • Two-way communication is processed in parallel using threads

Server side code: ChatServer.java

1
import java.io.*; import java.net.*; import java.util.*; public class ChatServer { private static final int PORT = 5000; private static List clientWriters = new ArrayList<>(); public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(PORT); System.out.println("Server started: listening on port " + PORT + "..."); while (true) { Socket socket = serverSocket.accept(); System.out.println("Client connections: " + socket); new ClientHandler(socket).start(); } } static class ClientHandler extends Thread { private Socket socket; private PrintWriter out; public ClientHandler(Socket socket) { this.socket = socket; } public void run() { try ( BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); ) { out = new PrintWriter(socket.getOutputStream(), true); clientWriters.add(out); String msg; while ((msg = in.readLine()) != null) { System.out.println("Received: " + msg); for (PrintWriter writer : clientWriters) { writer.println(msg); } } } catch (IOException e) { System.out.println("Communication error: " + e.getMessage()); } finally { if (out != null) clientWriters.remove(out); try { socket.close(); } catch (IOException e) { System.out.println("Failed to close socket"); } } } } }

Client side code: ChatClient.java

1
import java.io.*; import java.net.*; public class ChatClient { public static void main(String[] args) throws IOException { Socket socket = new Socket("localhost", 5000); System.out.println("Connected to server"); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); new Thread(() -> { try { String fromServer; while ((fromServer = in.readLine()) != null) { System.out.println("From server: " + fromServer); } } catch (IOException e) { System.out.println("Read error"); } }).start(); String input; while ((input = stdIn.readLine()) != null) { out.println(input); } socket.close(); } }

Common errors and solutions

  • Port in use
    → Solution:5000If the port number is being used by another app, change it.
  • I don't receive messages
    → Solution:PrintWriterofautoFlush=trueSpecifying this will send it immediately.
  • Crashes when multiple people are connected
    → Solution:synchronizedYou can deliver content securely by controlling access using the following (simplified in this example).

Application ideas for even more practical use

  • GUI chat screen (SwingorJavaFX) added
  • Named chat (enter nickname)
  • Message history storage feature
  • Sending and receiving stamps and emojis (binary processing)

Summary of the final configuration

  • ChatServer.java: Connection acceptance and message delivery processing
  • ChatClient.java: User input and server reception processing
  • Communication method:Socket(TCP communication)
  • Concurrency: The serverThreadSupports multiple clients, and clients also process reception in a separate thread

Summary: You can learn real-time communication with Java

In this article,How to create real-time chat using Java Socket communicationWe introduced the following.

What you'll gain from this article:

  • Client-Server Communication Basics
  • SocketandThreadTwo-way processing by combining
  • Error handling and parallel processing concepts

The chat app is simple yet deep.The best learning material for network programmingis.
Please try using it and develop it into your own unique chat tool!

Copied title and URL