Java sockets provide a way for programs to communicate over a network. In this blog post, we'll demonstrate how to set up socket communication in a Spring Boot application. We will cover both the server-side and client-side implementation.
Prerequisites
Before we begin, ensure you have the following:
- JDK 8 or higher
- Spring Boot
- An IDE (such as IntelliJ IDEA or Eclipse)
Step 1: Create a Spring Boot Project
First, create a new Spring Boot project using Spring Initializr with the following dependencies:
- Spring Web
Step 2: Implement the Server-Side Socket
Create a service class that will handle the socket communication on the server side. This class will create a server socket and listen for incoming connections.
ServerSocketService.java
package com.example.socketdemo.service;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
@Service
public class ServerSocketService {
private static final int PORT = 8081;
@PostConstruct
public void startServer() {
new Thread(() -> {
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Server is listening on port " + PORT);
while (true) {
Socket socket = serverSocket.accept();
new ClientHandler(socket).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
private static class ClientHandler extends Thread {
private final Socket socket;
public ClientHandler(Socket socket) {
this.socket = socket;
}
public void run() {
try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
String message;
while ((message = in.readLine()) != null) {
System.out.println("Received: " + message);
out.println("Echo: " + message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
This service will:
- Start a server socket on port 8081.
- Accept incoming client connections.
- Handle each client connection in a separate thread.
Step 3: Implement the Client-Side Socket
Create a command-line client that will connect to the server and send messages.
SocketClient.java
package com.example.socketdemo.client;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SocketClient {
private static final String SERVER_ADDRESS = "localhost";
private static final int SERVER_PORT = 8081;
public static void main(String[] args) {
try (Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {
System.out.println("Connected to the server. Type your messages:");
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("Server response: " + in.readLine());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This client will:
- Connect to the server at localhost on port 8081.
- Send messages typed by the user to the server.
- Receive and print the server's response.
Step 4: Run the Application
- Run the Spring Boot application. This will start the server socket.
- Run the SocketClient class as a standalone Java application. This will start the client.
You should see the client connect to the server and be able to send and receive messages.
Conclusion
In this blog post, we've shown how to set up Java socket communication in a Spring Boot application. We've covered the creation of a server socket service that listens for incoming connections and a client that connects to the server to send and receive messages. Sockets are a powerful way to enable network communication in your applications, and with Spring Boot, it's straightforward to integrate them into your services.
'개발 > BACK' 카테고리의 다른 글
Exploring the Latest JDK Version: Advantages and Issues : JDK20 (0) | 2024.07.08 |
---|---|
Mastering Transaction Exception Handling in Spring Boot: A Comprehensive Guide (0) | 2024.07.08 |
ChatGPT 활용 방법 (0) | 2024.07.08 |
Using Java Reflection in a Spring Boot Application (0) | 2024.07.08 |
Understanding Java Reflection: A Comprehensive Guide (0) | 2024.07.08 |