栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot+uniapp的websocket使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot+uniapp的websocket使用

springboot+uniapp的websocket使用 java后端

主要是再小程序有个地方需要获取实时的订单 所以写样这么一部分 websocket操作其实很简单

pom依赖

 
		
			org.springframework.boot
			spring-boot-starter-websocket
		
		
			com.alibaba
			fastjson
			1.2.58
		

WebSocketConfig.java

package com.ruoyi.project.tool.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

   @Configuration
   public class WebSocketConfig {

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

}

WebSocketServer.java

package com.ruoyi.project.tool.websocket;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
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 com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.log4j.Log4j2;

import org.springframework.stereotype.Component;

   @ServerEndpoint("/db/imserver/{userId}")
   @Component
   @Log4j2
   public class WebSocketServer {
   //    static Log log=LogFactory.get(WebSocketServer.class);
   
   private static int onlineCount = 0;
   
   private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap<>();
   
   private Session session;
   
   private String userId = "";

   
      @OnOpen
      public void onOpen(Session session, @PathParam("userId") String userId) {
      this.session = session;
      this.userId = userId;
      log.info("userId:"+userId);
      if (webSocketMap.containsKey(userId)) {
      	webSocketMap.remove(userId);
      	

      	log.info("创建用户1");
      	webSocketMap.put(userId, this);
      	// 加入set中

      } else {
      	log.info("创建用户2");
      	webSocketMap.put(userId, this);
      	// 加入set中
      	addOnlineCount();
      	// 在线数加1
      }

      log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());

      try {
      	

      	Map map = new HashMap();
      	map.put("code","1");
      	map.put("msg","连接成功");
      	map.put("data","内容");
      	
      	sendMessage(JSON.toJSONString(map));

      //			webSocketMap.get("1").sendMessage("niubi");
      } catch (IOException e) {
      //            log.error("用户:"+userId+",网络异常!!!!!!");
      }
      }

   
      @OnClose
      public void onClose() {
      if (webSocketMap.containsKey(userId)) {
      	webSocketMap.remove(userId);
      	// 从set中删除
      	subOnlineCount();
      }
      log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
      }

   
      @OnMessage
      public void onMessage(String message, Session session) throws IOException {
      log.info("用户消息:" + userId + ",报文:" + message);
      log.info("11111111111111111111111111111111111111111111111111111111111111111111111111111111111");
      JSONObject wcAuthJson = JSON.parseObject(message);
      String toUserId = (String)wcAuthJson.get("toUserId");
      //		log.info("toUserId:"+wcAuthJson.get("toUserId"));
      String type = (String) wcAuthJson.get("type");
      //		log.info(toUserId+"===="+type);
      webSocketMap.get(toUserId).sendMessage(type);

      }


	
	@OnError
	public void onError(Session session, Throwable error) {

//        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
//        error.printStackTrace();
	}

	
	public void sendMessage(String message) throws IOException {
		this.session.getBasicRemote().sendText(message);
	}
	
	
	public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
		log.info("发送消息到:" + userId + ",报文:" + message);
	    if(userId.trim().length()>0&&webSocketMap.containsKey(userId)){
	        webSocketMap.get(userId).sendMessage(message);
	    }else{
	        log.error("用户"+userId+",不在线!");
	    }
	}
	
	public static synchronized int getOnlineCount() {
		return onlineCount;
	}
	
	public static synchronized void addOnlineCount() {
		WebSocketServer.onlineCount++;
	}
	
	public static synchronized void subOnlineCount() {
		WebSocketServer.onlineCount--;
	}

}
uniapp前端
websockets(){
               //连接
				uni.connectSocket({
					url:'ws://127.0.0.1:8010/db/imserver/1'
				})
               //打开websocket回调
				uni.onSocketOpen(function (res) {
				  console.log('WebSocket连接已打开!');
				});
               //连接失败回调
				uni.onSocketError(function (res) {
				  console.log('WebSocket连接打开失败,请检查!');
				  uni.showToast({
				  	title:'WebSocket连接打开失败,请检查!',
					icon:'none'
				  })
				});
                //服务端过来内容之后打印
				uni.onSocketMessage(function (res) {
				  console.log('收到服务器内容:' + res.data);
				  console.log('收到服务器内容:' + JSON.parse(res.data).msg);
				});
                //关闭websocket打印
				uni.onSocketClose(function (res) {
				  console.log('WebSocket 已关闭!');
				  uni.showToast({
				  	title:'WebSocket 已关闭!',
				  	icon:'none'
				  })
				});
			}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/696579.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号