springboot整合websocket

硅谷探秘者 2630 0 0

1.配置springboot支持websocket

package com.example.demo.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
 * websocket配置
 * @author jiajia
 */
@Configuration  
public class WebSocketConfig {  
    @Bean  
    public ServerEndpointExporter serverEndpointExporter() {  
        return new ServerEndpointExporter();  
    }  
}


2.websocket服务

package com.example.demo.websocket;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
/**
 * springboot集成websocket
 * @author jiajia
 */
@ServerEndpoint("/websocket/{id}")
@Component
public class WebSocketServer {
	public static final Object lock=new Object(); 
	/**
	 * 记录在线人数
	 */
    private static int onlineCount = 0;
    /**
     * WebSocketServer对象集合
     */
    private static final Map<String,WebSocketServer> webSocketMap = new HashMap<String,WebSocketServer>();
    /**
     * 回话
     */
    private Session session;
    /**
     * id标识
     */
    private String id;
    
    private AStar astar;

    /**
     * 连接成功时调用
     * @param session
     * @param sid
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("id") String id) {
        this.session = session;
        putObj(id);
        addOnlineCount();
        try {
        	sendMessage("{type:1,msg:'连接成功'}");
        } catch (IOException e){
        	
        }
    }

    /**
     * 连接关闭时调用
     */
    @OnClose
    public void onClose() {
    	delObj();
        subOnlineCount();
        System.out.println("删除"+this.id);
    }

    /***
     * 接受客户端发送消息时调用
     * @param message 消息
     * @param session 
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
        	Map<String,Object> map=JSON.parseObject(message);
        	System.out.println(map.get("type"));
        	if(map.containsKey("type")) {
	        	if(Integer.valueOf(map.get("type").toString()).equals(1)) {//请求地图
	        		astar = new AStar(this,Integer.valueOf(map.get("wid").toString()));
	        		String s=JSON.toJSONString(astar.NODES);
	        		sendMessage("{type:6,msg:"+s+"}");
	        		System.out.println("-");
	        	}else if(Integer.valueOf(map.get("type").toString()).equals(2)){//修改地图
	        		int x=Integer.valueOf(map.get("x").toString());
	        		int y=Integer.valueOf(map.get("y").toString());
	        		if(this.astar.NODES[x][y]==0) {
	        			this.astar.NODES[x][y]=1;
	        		}else {
	        			this.astar.NODES[x][y]=0;
	        		}
	        	}else if(Integer.valueOf(map.get("type").toString()).equals(3)){
	        		System.out.println(map);
	        		int startX=Integer.valueOf(map.get("startX").toString());
	        		int startY=Integer.valueOf(map.get("startY").toString());
	        		int endX=Integer.valueOf(map.get("endX").toString());
	        		int endY=Integer.valueOf(map.get("endY").toString());
	        		this.astar.begin(startX, startY, endX, endY);
	        	}
        	}
			sendMessage("{type:2,msg:'收到消息'}");
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
   /**
    * 给某个指定id发送消息
    * @param id
    * @return
    */
    public boolean sendMessageById(String id,String message) {
    	WebSocketServer obj=webSocketMap.get(id);
    	if(obj!=null) {
    		try {
				obj.sendMessage(message);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			}
    		return true;
    	}else {
    		return false;
    	}
    }
    
    /**
     * 群发消息
     * @param message
     * @return
     */
    public void sendMessageGroup(String message) {
    	synchronized (lock) {
    		for (Map.Entry<String,WebSocketServer> entry : webSocketMap.entrySet()) {
    			try {
					sendMessage(entry.getValue().session, message);
				} catch (IOException e) {
				}
    		}
		}
    }

	/**
	 * 连接发生异常时调用
	 * @param session
	 * @param error
	 */
    @OnError
    public void onError(Session session, Throwable error) {
    	System.out.println("链接异常");
    	delObj();
        subOnlineCount();
        error.printStackTrace();
    }
    
	/**
	 * 服务器向本次连接的前端发送消息
	 * @param message
	 * @throws IOException
	 */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
    
    /**
     * 向某链接发送消息
     * @param session
     * @param message
     * @throws IOException
     */
    private void sendMessage(Session session,String message) throws IOException {
        session.getBasicRemote().sendText(message);
    }

    /**
     * 向webSocketMap集合中添加此对象的引用
     * @param id 
     */
    private void putObj(String id) { 
    	synchronized (lock){
    		if(!webSocketMap.containsKey(id)) {
    			webSocketMap.put(id,this);
    			this.id=id;
    			System.out.println(id+"链接成功:"+getOnlineCount());
    		}
		}
    }
    
    /**
     * 从webSocketMap中删除对本对象的引用
     */
    private void delObj() {
    	synchronized (lock){
    		webSocketMap.remove(this.id);
    	}
    }

    /**
     * 获取在线人数
     * @return
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    /**
     * 在线人数+1
     */
    private static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    /**
     * 在线人数-1
     */
    private static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}



评论区
请写下您的评论...
暂无评论...
猜你喜欢
框架 2519 springbootmybatis1.创建maven项目2.sql文件SETNAMESutf8mb4;SETFOREIGN_KEY_CHECKS=0
weblog 982 pomparent groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-parent/artifactId version2.1.3.RELEASE/version /parentdependencies dependency groupIdorg.springframework.boot/group
java框架 1378 springbootelasticsearch框架实现全文索引demo配置说明参考:http://www.jiajiajia.club/blog/artical/Ja4t7X/378
框架 2378 安装redis数据库参考:http://www.jiajiajia.club/blog/artical/166redis配置详解参考:http://www.jiajiajia.club/blog/artical/210安装完数据库以后如果不是本地连接记得修改密码requirepass。默认是没有密码需要后台运行修改daemonizeyes默认是noyml配置文件spring:redis:host:
框架 1451 1.pom文件dependencygroupIdorg.apache.shiro/groupIdartifactIdshiro-spring/artifactIdversion1.4.0/version/dependencydependency groupIdorg.apache.shiro/groupId artifactIdshiro-ehcache/artifactId vers
框架 2301 springboot视图层,官方推荐使用thymeleaf。thymeleaf只是渲染html的一种方式,是一种模板。第一步创建一个maven项目第二步:修改Jdk版本,添加thymeleaf
框架 1304 版本说明,不同的springboot版本也对应着不同的elasticsearch版本,如果版本不对应客户端和服务端都会报相应的错误,对应关系请自行百度,本次测试的版本如下:springboot版本
official 642 [TOC]一、pom文件?xmlversion="1.0"encoding="UTF-8"?projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
归档
2018-11  12 2018-12  33 2019-01  28 2019-02  28 2019-03  32 2019-04  27 2019-05  33 2019-06  6 2019-07  12 2019-08  12 2019-09  21 2019-10  8 2019-11  15 2019-12  25 2020-01  9 2020-02  5 2020-03  16 2020-04  4 2020-06  1 2020-07  7 2020-08  13 2020-09  9 2020-10  5 2020-12  3 2021-01  1 2021-02  5 2021-03  7 2021-04  4 2021-05  4 2021-06  1 2021-07  7 2021-08  2 2021-09  8 2021-10  9 2021-11  16 2021-12  14 2022-01  7 2022-05  1 2022-08  3 2022-09  2 2022-10  2 2022-12  5 2023-01  3 2023-02  1 2023-03  4 2023-04  2 2023-06  3 2023-07  4 2023-08  1 2023-10  1 2024-02  1 2024-03  1
标签
算法基础 linux 前端 c++ 数据结构 框架 数据库 计算机基础 储备知识 java基础 ASM 其他 深入理解java虚拟机 nginx git 消息中间件 搜索 maven redis docker dubbo vue 导入导出 软件使用 idea插件 协议 无聊的知识 jenkins springboot mqtt协议 keepalived minio mysql ensp 网络基础 xxl-job rabbitmq haproxy srs 音视频 webrtc javascript
目录
没有一个冬天不可逾越,没有一个春天不会来临。最慢的步伐不是跬步,而是徘徊,最快的脚步不是冲刺,而是坚持。