Create a Simple Chat Application Using Socket.IO in Java
A detailed guide on how to create a simple chat application using Java and Socket.IO. This article will help you understand how to set up a server and client for real-time communication.
This article will guide you in building a simple chat application using Socket.IO in Java. We will set up a server using Spring Boot and a client using Java Swing to create a user interface. The application will allow users to send and receive messages in real-time.
Java Code
1. Setting up the server with Spring Boot
// build.gradle
plugins {
id 'org.springframework.boot' version '3.0.0'
id 'io.spring.dependency-management' version '1.0.12.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-websocket'
implementation 'org.springframework.boot:spring-boot-starter'
}
tasks.named('test') {
useJUnitPlatform()
}
// WebSocketConfig.java
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat").withSockJS();
}
}
// ChatController.java
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
@Controller
public class ChatController {
private final SimpMessagingTemplate messagingTemplate;
public ChatController(SimpMessagingTemplate messagingTemplate) {
this.messagingTemplate = messagingTemplate;
}
@MessageMapping("/send")
public void sendMessage(String message) {
messagingTemplate.convertAndSend("/topic/messages", message);
}
}
2. Setting up the client with Java Swing
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
public class ChatClient extends WebSocketClient {
private JTextArea textArea;
private JTextField textField;
public ChatClient(String serverUri, JTextArea textArea, JTextField textField) {
super(new URI(serverUri));
this.textArea = textArea;
this.textField = textField;
}
@Override
public void onOpen(ServerHandshake handshakedata) {
System.out.println("Connected to server");
}
@Override
public void onMessage(String message) {
textArea.append(message + "\n");
}
@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("Disconnected from server");
}
@Override
public void onError(Exception ex) {
ex.printStackTrace();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Chat Application");
JTextArea textArea = new JTextArea(20, 30);
JTextField textField = new JTextField(30);
JButton sendButton = new JButton("Send");
frame.getContentPane().add(new JScrollPane(textArea), "Center");
frame.getContentPane().add(textField, "South");
frame.getContentPane().add(sendButton, "South");
ChatClient client = new ChatClient("ws://localhost:8080/chat", textArea, textField);
client.connect();
sendButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String message = textField.getText();
client.send(message);
textField.setText("");
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Detailed explanation:
-
Server:
-
WebSocketConfig
: Configures WebSocket with Spring Boot, enabling STOMP for message sending. -
ChatController
: Receives and processes messages sent from the client, broadcasting to all connected clients.
-
-
Client:
-
ChatClient
: Connects to the WebSocket server and manages sending and receiving messages. Uses Java Swing to create the user interface for the chat application.
-
System Requirements:
- Java 17 or higher
- Spring Boot 3.0 or higher
- WebSocket library
How to install the libraries needed to run the Java code above:
Use Gradle for dependency management. Run the command gradle build
in the directory containing build.gradle
to install the required libraries.
Tips:
- Make sure the server is running before starting the client.
- Explore STOMP further to expand the features of your chat application.