websocket基础

websocket基础_第1张图片

 websocket基础_第2张图片

下面就以代码来进行说明

1,先导入websocket依赖

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

2.编写websocket相关bean管理配置

@Configuration
public class config {
    //申明websocket是由bean管理的
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3.编写业务层代码

@ServerEndpoint("/api/{user_id}")
@Component
public class servlet {

    private  String id;
    //客户端建立
    @OnOpen
    public  void  onopen(Session  session,  @PathParam("user_id")String id){
        this.id=id;
        try {
            session.getBasicRemote().sendText("连接建立成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("连接建立");
    }
   //客户端发送消息,服务端接受
    @OnMessage
    public  void  onoMessage(String  message,  Session session){
        System.out.println(message);
        try {
            //向客户端返还信息
            session.getBasicRemote().sendText("消息收到");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //客户端关闭时候
    @OnClose
    public  void  onoClose(Session  session,  @PathParam("user_id")String id){
        this.id=id;
        System.out.println("连接关闭");
    }
}

注意@ServerEndpoint("/api/{user_id}")此注解供websocket提供访问连接url

4.附赠前端代码一份




    
    
    
    Document





5.代码一些关键解析

websocket基础_第3张图片

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