0Pricing
WebSockets & Real-Time Systems with Spring · Урок

Базовый обмен сообщениями между клиентом и сервером

Реализуйте простую отправку сообщений от клиента к серверу и обратно, продемонстрировав базовое взаимодействие в реальном времени.

«Базовый обмен сообщениями между клиентом и сервером» — бесплатный урок WebSockets & Real-Time Systems with Spring на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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) и разблокировать остальной курс WebSockets & Real-Time Systems with Spring, подпишись на CoddyKit PRO. Курс WebSockets & Real-Time Systems with Spring содержит 4 уроков всего.

Чему я научусь в уроке «Базовый обмен сообщениями между клиентом и сервером»?

Реализуйте простую отправку сообщений от клиента к серверу и обратно, продемонстрировав базовое взаимодействие в реальном времени. Ты практикуешь WebSockets & Real-Time Systems with Spring с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать WebSockets & Real-Time Systems with Spring?

Предыдущий опыт не требуется. WebSockets & Real-Time Systems with Spring на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Базовый обмен сообщениями между клиентом и сервером»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке WebSockets & Real-Time Systems with Spring?

Да. Каждый урок WebSockets & Real-Time Systems with Spring включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Spring Boot для WebSockets
  2. Настройка конечных точек WebSocket
  3. Базовый обмен сообщениями между клиентом и сервером
  4. Обработка событий жизненного цикла WebSocket в Spring
← Назад к WebSockets & Real-Time Systems with Spring