将 Java WebSockets (JSR-356) 与 SpringBoot 集成

Hal*_*lex 2 spring websocket spring-boot jsr356

我在 SpringBoot 中部署 websocket 时遇到问题。我已经尝试了很多基于https://spring.io/blog/2013/05/23/spring-framework-4-0-m1-websocket-support的方法,使用Java API for WebSocket(JSR-356)与 Spring Boot等没有任何运气。

这是我正在尝试的:

网络套接字:

@ServerEndpoint(value="/socket/{name}", configurator = SpringConfigurator.class)
public class TestSocket {

    public ApiSocket(){}

    @OnOpen
    public void onOpen(
                Session session,
                @PathParam("name") String name) throws IOException {

        session.getBasicRemote().sendText("Hi " + name);
    }
}
Run Code Online (Sandbox Code Playgroud)

应用程序.属性:

server.contextPath=/api
Run Code Online (Sandbox Code Playgroud)

主要类别:

@SpringBootApplication
public class Main {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Main.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

根据上面的博客文章,这应该就是所需要的。我还尝试了所描述的第二种方法,该方法涉及一个没有运气的豆:

  @Bean
  public ServerEndpointExporter endpointExporter() {
      return new ServerEndpointExporter();
  }
Run Code Online (Sandbox Code Playgroud)

我正在尝试打开到 ws://localhost:8080/api/socket/John 的连接,并期望收到带有路径名的响应:

var socket = new WebSocket('ws://localhost:8080/api/socket/John');
Run Code Online (Sandbox Code Playgroud)

握手期间的结果是 404。

sus*_*097 5

您还必须在 Spring 配置中的 Bean 中添加 TestSocket 并configurator = SpringConfigurator.class从 TestSocket 中删除。

一般来说,Spring 通过其 STOMP 协议覆盖普通的 java JSR 356 websocket,该协议是 websocket 的一部分。它也不支持像普通 websocket 那样的完全二进制消息。您应该ServerEndpointExporter在配置中添加如下:

@Configuration
public class EndpointConfig 
{
    @Bean
    public ChatEndpointNew chatEndpointNew(){
        return new ChatEndpointNew();
    }


    @Bean
    public ServerEndpointExporter endpointExporter(){
        return new ServerEndpointExporter();
    }

}
Run Code Online (Sandbox Code Playgroud)

让我们看看客户端连接的房间的完整聊天消息:

@ServerEndpoint(value="/chatMessage/{room}")
public class ChatEndpointNew 
{

    private final Logger log = Logger.getLogger(getClass().getName());

    @OnOpen
    public void open(final Session session, @PathParam("room")final String room)
    {
        log.info("session openend and bound to room: " + room);
        session.getUserProperties().put("room", room);
        System.out.println("session openend and bound to room: " + room);
    }

    @OnMessage
    public void onMessage(final Session session, final String message) {
        String room = (String)session.getUserProperties().get("room");
        try{
            for (Session s : session.getOpenSessions()){
                if(s.isOpen()
                          && room.equals(s.getUserProperties().get("room"))){
                    String username = (String) session.getUserProperties().get("username");
                    if(username == null){
                        s.getUserProperties().put("username", message);
                        s.getBasicRemote().sendText(buildJsonData("System", "You are now connected as:"+message));
                    }else{
                        s.getBasicRemote().sendText(buildJsonData(username, message));      
                    }
                }
            }
        }catch(IOException e) {
            log.log(Level.WARNING, "on Text Transfer failed", e);
        }
    }

    @OnClose
    public void onClose(final Session session){
        String room = (String)session.getUserProperties().get("room");
        session.getUserProperties().remove("room",room);
        log.info("session close and removed from room: " + room);
    }

    private String buildJsonData(String username, String message) {
        JsonObject jsonObject = Json.createObjectBuilder().add("message", "<tr><td class='user label label-info'style='font-size:20px;'>"+username+"</td>"+"<td class='message badge' style='font-size:15px;'> "+message+"</td></tr>").build();
        StringWriter stringWriter = new StringWriter();
        try(JsonWriter jsonWriter = Json.createWriter(stringWriter)){
            jsonWriter.write(jsonObject);
        }

        return stringWriter.toString();
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,您应该将 ChatEndpointNew 和 ServerEndpointExporter 与应用程序的主 Spring 配置分开添加。如果出现任何错误,请尝试以下操作:

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-websocket</artifactId>
   <version>4.0.0.RELEASE</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

您还可以阅读Spring 文档。