websocket 简单理解

服务端

maven依赖

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

配置类 WebSocketConfig,注入ServerEndpointExporter 服务端点出口

@Configuration  
public class WebSocketConfig {  
    
    @Bean  
    public ServerEndpointExporter serverEndpointExporter() {  
        return new ServerEndpointExporter();  
    }  
  
}

编写 WebSocketServer 前端访问 /imserver/{userId} 建立一个TCP 连接

@ServerEndpoint("/imserver/{userId}")

@Component

public class WebSocketServer {}

WebSocketServer里维护一个ConcurrentHashMap,key为userId,value是一个WebSockertServer , 这个里面有 session,@OnOpen(建立连接),@OnClose(关闭连接),@OnMessage(向客户端发送消息),@OnError(监听错误消息)

private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();

客户端(浏览器)

var socketUrl="http://localhost:9999/demo/imserver/"+$("#userId").val();
            socketUrl=socketUrl.replace("https","ws").replace("http","ws");
            console.log(socketUrl);
            if(socket!=null){
                socket.close();
                socket=null;
            }
            socket = new WebSocket(socketUrl);
创建 socket

socket.onopen //打开

socket.onmessage // 获取服务端的消息

socket.onclose // 关闭

socket.onerror // 监听错误事件

socket.send // 向服务端 发送消息

参考文章链接

http://t.csdn.cn/anvzR

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值