1. 添加依赖
首先,在pom.xml
中添加spring-boot-starter-websocket
依赖,正如你已经指出的:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
2. 创建WebSocket配置
创建一个配置类来启用和配置WebSocket。
import org.springframework.context.annotation.Configuration
import org.springframework.web.socket.config.annotation.EnableWebSocket
import org.springframework.web.socket.config.annotation.WebSocketConfigurer
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry
@Configuration
@EnableWebSocket
open class WebSocketConfig : WebSocketConfigurer {
override fun registerWebSocketHandlers(registry: WebSocketHandlerRegistry) {
registry.addHandler(EchoWebSocketHandler(), "/echo")
}
}
3. 创建WebSocket处理器
创建一个WebSocketHandler
来处理消息。
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
public class EchoWebSocketHandler extends TextWebSocketHandler {
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// Echo the received message back
session.sendMessage(message);
}
}
4. 启动Spring Boot应用程序
创建Application.java
来启动应用程序。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
5. 创建WebSocket客户端
这里是一个简单的WebSocket客户端示例,使用标准Java WebSocket API。
import jakarta.websocket.ClientEndpoint
import jakarta.websocket.ContainerProvider
import jakarta.websocket.OnMessage
import jakarta.websocket.Session
import java.net.URI
@ClientEndpoint
class EchoClient {
@OnMessage
fun onMessage(message: String, session: Session?) {
println("Received from server: $message")
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
try {
val container = ContainerProvider.getWebSocketContainer()
val uri = "ws://localhost:8080/echo"
val session: Session = container.connectToServer(EchoClient::class.java, URI.create(uri))
session.getBasicRemote().sendText("Hello, echo!")
Thread.sleep(1000)
session.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
启动并测试
启动Spring Boot应用程序,然后运行客户端。客户端会发送一条消息到服务器,服务器应该会把相同的消息回传给客户端。