websocket基础

 

下面就以代码来进行说明

1,先导入websocket依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

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.附赠前端代码一份

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
<input id="input"  type="text" placeholder="输入你的内容">
<button id="but">发送请求</button>
<div id="div1" style="width: 200px;height: 200px; background:yellow;"></div>
<script>
    let input = document.getElementById("input");
    let but = document.getElementById("but");
    let div1 = document.getElementById("div1");
     //参数1:websocket服务地址
      var socket=new WebSocket("ws://localhost:8080/api/1");
      //open:当websocket服务连接成功
      socket.addEventListener("open",function (){
           div1.innerHTML="连接服务成功了"
          //客户端发送消息
          socket.send("发送成功")
      })
    //message:接受客户端的信息
    socket.addEventListener("message",function (re){
        console.log(re.data)

    })
    //客户端关闭时
    socket.addEventListener("close",function (){
         div1.innerHTML="我已经离开了"
    })
</script>
</body>
</html>

5.代码一些关键解析

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值