java ssm/springBoot 实现websocke

java ssm/springBoot 实现websocke

服务端 + h5 示例代码

1. 服务端

@ServerEndpoint(value = "/websocket/{userId}")
public class WebSocket {
	
	private static int onlineCount = 0;//连接数

	private static Map<String, WebSocket> clients = new ConcurrentHashMap<>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    private Integer userId;
    private String uuid;
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("userId")Integer userId, Session session) throws Exception{
		this.uuid = SysUtil.get32UUID();//
		clients.put(this.uuid, this);
		this.userId = userId;
		WebSocket.onlineCount++;
        this.session = session;
    }
 
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() throws IOException{
        //从map中删除
		clients.remove(this.uuid);
		WebSocket.onlineCount--;
    }
 
    /**
     * 收到客户端消息后调用的方法,通知
	*/
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
		sendMessage(message);
    }
 
    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error){
        error.printStackTrace();
    }
 
 
    /**
     * 给其它页面发消息发送消息。
     */
    public void sendMessageTo(String message){
    	for (WebSocket item : clients.values()){
    		if(!item.uuid.equals(this.uuid)){
    			item.session.getAsyncRemote().sendText(message);
			}
		}
    }

    /**
     * 对所有页面发送消息
     */
    public void sendMessageToAll(String message){
        for (WebSocket item : clients.values()){
			item.session.getAsyncRemote().sendText(message);
        }
    }
	
    /**
     * 发送消息方法
     */
    public void sendMessage(String message) throws IOException{
    	this.session.getBasicRemote().sendText(message);
    }


}

public class SysUtil {
	/**
	 * 32位的UUid
	 */
	public static String get32UUID() {
		return UUID.randomUUID().toString().replace("-", "");
	}
}

2. h5

var websocket = null; 
  
//判断当前浏览器是否支持WebSocket  
if ('WebSocket' in window) {  
	websocket = new WebSocket("ws://ip:port/demo/websocket/123");  
} else {  
	alert('当前浏览器 Not support websocket')  
}  
  
//连接发生错误的回调方法  
websocket.onerror = function() {  
	console.log("WebSocket连接发生错误");  
};  
  
//连接成功建立的回调方法  
websocket.onopen = function(event) {
	console.log("WebSocket连接成功");  
}  
  
//接收到消息的回调方法  
websocket.onmessage = function(event) {
	console.log(event.data);  
}  
  
//连接关闭的回调方法  
websocket.onclose = function(event) {  
	console.log("WebSocket连接关闭");  
}  
  
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。  
window.onbeforeunload = function() {  
	closeWebSocket();  
}  
  
//关闭WebSocket连接  
function closeWebSocket() {  
	websocket.close();  
}  

function sendMessage(msg){
	websocket.send(msg);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值