WebSocket

简介

WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。

HTTP协议在浏览器和服务器交互时,在完成一次数据传输后,就会断开。并且只能由浏览器向服务器发出请求,因此在需要实时更新时,只能利用Ajax进行轮询,频繁连接服务器。

webSocket则只需要进行一次连接后,就可以一直相互发送数据。

1607586397190.png

其中websocket中http连接和普通的http连接有所不同,

客户端向服务器发出HTTP请求:

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com

其中关注:

Upgrade: websocket
Connection: Upgrade
这是告诉服务器,升级为websocket请求

服务器向客户端回复

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

这样就完成了websocket连接。

简易聊天室

简易聊天室——大体流程:

(1)用户输入用户名和密码,点击登录

(2)后台UserController.login将用户名存入HttpSession,跳转到message.html页面

(3)进入message.html页面,建立websocket连接,后台响应onOpen事件,从EndpointConfig中取出HTTPSession,然后在从httpSession中取出用户名,然后以用户名为key,该websocket对象为值,存入onLineUsers中。

(4)用户输入要发送人的用户名和消息,点击发送。ajax带着表单信息请求到后台sendMessage接口,后台根据要发送的用户名,在onLineUsers中取出相应的websocket对象,进行消息发送。

(5)被发送用户,响应onmessage事件,将消息弹窗显示

服务器端

依赖:


            org.springframework.boot
            spring-boot-starter-web
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-websocket
        
    

首先,新建webSocket的配置类:

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @author yuanwei
 * @date 2020/12/8 17:21
 * @description
 */
@Component
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

接着构建websocket事件类

import com.example.websocket.config.GetHttpSessionConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yuanwei
 * @date 2020/12/8 18:01
 * @description
 */
@Component
@ServerEndpoint(value="/webSocket",configurator = GetHttpSessionConfig.class)
@Slf4j
public class WebSocket {

    private Session session;

    private static Map onLineUsers=new ConcurrentHashMap<>();

    private HttpSession httpSession;

    @OnOpen
    public void onOpen(Session session, EndpointConfig endpointConfig){
        this.session = session;
        this.httpSession = (HttpSession) endpointConfig.getUserProperties().get(HttpSession.class.getName());
        onLineUsers.put((String)this.httpSession.getAttribute("user"),this);
        log.info("【websocket消息】有新的连接,总数:{}",onLineUsers.size());
    }

    @OnClose
    public void onClose(EndpointConfig endpointConfig){
        onLineUsers.remove(this.httpSession.getAttribute("user"));
        log.info("【websocket消息】连接断开,总数:{}",onLineUsers.size());
    }

    @OnMessage
    public void onMessage(String message){
        log.info("【websocket消息】收到客户端发来的消息:{}",message);
    }

    public void sendMessage(String toUsername,String message){
        try{
            if(onLineUsers.containsKey(toUsername)){
                onLineUsers.get(toUsername).session.getBasicRemote().sendText(message);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

UserController:只为区分不同用户,不进行校验用户名和密码

@Controller
public class UserController {

    @PostMapping("/login")
    public String login(String name, String password, HttpSession session){
        session.setAttribute("user",name);
        return "./message.html";
    }
}

WebSocketController:用于浏览器端发送消息

import com.example.websocket.service.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author yuanwei
 * @date 2020/12/9 9:52
 * @description
 */
@RestController
public class WebSocketController {

    @Autowired
    private WebSocket webSocket;

    @PostMapping("/sendMessage")
    public void sendMessage(String toUsername,String message){
        try{
            webSocket.sendMessage(toUsername,message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

GetHttpSessionConfig:获取HttpSession,并将之存储在ServerEndpointConfig,以供websocket获取httpSession中的用户名。(如不需该操作,可省略)

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;

/**
 * @author yuanwei
 * @date 2020/12/10 17:22
 * @description
 */
public class GetHttpSessionConfig extends ServerEndpointConfig.Configurator {

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        HttpSession httpSession = (HttpSession) request.getHttpSession();
        sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
    }
}

浏览器端

登录页面,只为其用户名




    
    
    

    
    

    
    
    Title


    

发送消息页面:




    
    Title
    
    

    
    

    
    


    

你可能感兴趣的:(WebSocket)