0Pricing
WebSockets & Real-Time Systems with Spring · 강의

기본 클라이언트-서버 메시징

클라이언트에서 서버로, 서버에서 클라이언트로 간단한 메시지를 보내는 기능을 구현하여 기본적인 실시간 상호 작용을 익힙니다.

기본 클라이언트-서버 메시징은(는) CoddyKit의 무료 WebSockets & Real-Time Systems with Spring 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebSockets & Real-Time Systems with Spring 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebSockets & Real-Time Systems with Spring 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Messaging Fundamentals

In previous lessons, you set up your Spring WebSocket application and configured its endpoints. Now, let's make it talk!

Real-time communication is all about sending messages back and forth between clients (like web browsers) and the server. This lesson will show you the basics of how this interaction works.

Client Sends to Server

The most common interaction starts with a client sending a message to the server. This message might be a user action, a chat message, or a command.

  • The client establishes a WebSocket connection.
  • It then sends data to a specific server "destination".
  • Spring handles receiving this message on the server side.

Server-Side Receiver (Spring)

Spring uses annotations to make handling incoming messages easy. The @MessageMapping annotation maps a method to a specific destination path, similar to @GetMapping for HTTP.

When a client sends a message to, say, /app/hello, the method annotated with @MessageMapping("/hello") will be invoked.

Implementing Server Receiver

Let's see a simple server-side method that receives a message. Notice how the input message can be directly mapped to a Java object (e.g., a String).

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.stereotype.Controller;

@Controller
public class GreetingController {

    @MessageMapping("/hello")
    public String handleHello(String message) {
        System.out.println("Received from client: " + message);
        return "Server received: " + message; 
    }
}

Server Sends to Client

After processing a client's message, the server often needs to send a response or broadcast updates to clients. This is how real-time interaction truly happens.

Spring provides convenient ways to send messages back to clients, often using a message broker.

Implementing Server Sender

To send an immediate response to the client who sent the message, you can use the @SendTo annotation. This routes the return value of your @MessageMapping method to a specific topic.

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

@Controller
public class GreetingController {

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public String handleHello(String message) {
        System.out.println("Received: " + message);
        return "Hello from Server: " + message;
    }
}

Client-Side Sending (JavaScript)

On the client side, typically a web browser, you'll use JavaScript to interact with the WebSocket endpoint. Libraries like SockJS and STOMP.js simplify this process.

  • Connect to the WebSocket endpoint.
  • Send messages to the server's @MessageMapping destinations.
  • Subscribe to server "topic" destinations to receive messages.

Simple JavaScript Client

Here's how a basic JavaScript client sends a message. It uses a STOMP client to connect and send data to the server's /app/hello destination.

// This assumes SockJS and STOMP.js are loaded
var socket = new SockJS('/ws'); // Your WebSocket endpoint
var stompClient = Stomp.over(socket);

stompClient.connect({}, function (frame) {
    console.log('Connected: ' + frame);

    // Subscribe to a topic to receive messages
    stompClient.subscribe('/topic/greetings', function (greeting) {
        console.log("Received from server: " + greeting.body);
    });

    // Send a message to the server
    stompClient.send("/app/hello", {}, "Hello Spring!");
});

Full Echo Example (Server)

Let's put it together! This Spring Boot server will receive a message, print it, and then send a greeting back to a public topic. You can run this as a Spring Boot application.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@SpringBootApplication
public class WebSocketServerApp {
    public static void main(String[] args) {
        SpringApplication.run(WebSocketServerApp.class, args);
    }
}

@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").withSockJS(); // WebSocket endpoint
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic"); // Enable a simple broker for /topic destinations
        config.setApplicationDestinationPrefixes("/app"); // Client messages for @MessageMapping
    }
}

@Controller
class GreetingController {
    @MessageMapping("/hello") // Client sends to /app/hello
    @SendTo("/topic/greetings") // Server sends response to /topic/greetings
    public String greet(String message) throws Exception {
        Thread.sleep(1000); // Simulate processing delay
        System.out.println("Server received: " + message);
        return "Server says: " + message + "!";
    }
}

Message Flow Check

Consider a Spring WebSocket application where a client sends a message to /app/chat and the server responds to /topic/updates. Which of the following statements are true about this interaction?

Recap: Basic Messaging

Great job! You've learned the fundamentals of client-server messaging in Spring WebSockets:

  • Clients send messages to server destinations using client-side STOMP libraries.
  • Servers receive messages using @MessageMapping.
  • Servers can respond immediately using @SendTo to broadcast to topics.

This forms the foundation for all real-time interactions. Next, we'll dive deeper into the STOMP protocol for more structured messaging!

자주 묻는 질문

“기본 클라이언트-서버 메시징” 강의는 무료인가요?

네 — “기본 클라이언트-서버 메시징” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Real-Time Systems with Spring 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Real-Time Systems with Spring 강의에는 총 4개의 강의가 포함되어 있습니다.

“기본 클라이언트-서버 메시징”에서 뭘 배우나요?

클라이언트에서 서버로, 서버에서 클라이언트로 간단한 메시지를 보내는 기능을 구현하여 기본적인 실시간 상호 작용을 익힙니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Real-Time Systems with Spring을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

WebSockets & Real-Time Systems with Spring을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Real-Time Systems with Spring은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“기본 클라이언트-서버 메시징” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 WebSockets & Real-Time Systems with Spring 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 WebSockets & Real-Time Systems with Spring 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. WebSockets를 위한 Spring Boot
  2. WebSocket 엔드포인트 구성
  3. 기본 클라이언트-서버 메시징
  4. Spring에서 WebSocket 수명 주기 이벤트 처리
← WebSockets & Real-Time Systems with Spring(으)로 돌아가기