websocket

一、聊天室模式

0.效果图:

websocket_第1张图片

1.后端代码

1.1 导入依赖

    
            org.springframework.boot
            spring-boot-starter-websocket
            
                
                    org.springframework.boot
                    spring-boot-starter-web
                
            
    

1.2 WebSocket工具类

package com.woniu.util;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WebSocketUtil {

    
    //放所有参与聊天的用户标识
    public static final Map messageMap = new ConcurrentHashMap<>();

    /**
    *单个消息
    */
    public static void send(Session session,String message){
        if (session != null){
            final RemoteEndpoint.Basic basic = session.getBasicRemote();
            if (basic != null){
                try {
                    basic.sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
    * 全体发消息
    */
    public static void sendAll(String message){
        messageMap.forEach((userName,session) -> send(session,message));
    }

}

 1.3 WebSocket事件类

package com.woniu.webscoket;

import com.woniu.util.WebSocketUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@RestController
@ServerEndpoint("/WebSocketHandler/{userName}")
public class WebSocketHandler {
    @OnOpen
    public void openSession(@PathParam("userName") String userName, Session session){
        String message = "欢迎:"+userName +"加入群聊";
        WebSocketUtil.messageMap.put(userName,session);
        //给所有人发消息
        WebSocketUtil.sendAll(message);

    }
    @OnMessage
    public void onMessage(@PathParam("userName") String userName, String message){
        message = userName +":" +message;
        WebSocketUtil.sendAll(message);
    }


    @OnClose
    public void onClose(@PathParam("userName") String userName,Session session){
        WebSocketUtil.messageMap.remove(userName);
        WebSocketUtil.sendAll("用户:"+userName+"离开聊天室");

        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

1.4 WebSocketConfig 配置类, 并在主启动类上加上 @EnableWebSocket 注解

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter(){

        return new ServerEndpointExporter();
    }
}

1.5 如果用了网关或springSecurity 记得配白名单

2. 前端代码【完整】





问题:

如果你在配置完成后, 出现这个提示 

WebSocket connection to 'ws://xxx/WebSocketHandler/e' failed

websocket_第2张图片

要去检查一下,你在前端请求的端口是否正确。

websocket_第3张图片

二、私聊模式 (未完待续)

...

你可能感兴趣的:(websocket,网络协议,网络)