springboot+uniapp的websocket使用

springboot+uniapp的websocket使用

java后端

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

pom依赖

 <!-- springboot整合websocket -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-websocket</artifactId>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.58</version>
		</dependency>

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;
/**

 * 开启WebSocket支持

 * @author zhengkai
   */
   @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;
/**

 * WebSocketServer

 * 

 * @author zhengkai.blog.csdn.net
   */
   @ServerEndpoint("/db/imserver/{userId}")
   @Component
   @Log4j2
   public class WebSocketServer {
   //    static Log log=LogFactory.get(WebSocketServer.class);
   /** 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 */
   private static int onlineCount = 0;
   /** concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。 */
   private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
   /** 与某个客户端的连接会话,需要通过它来给客户端发送数据 */
   private Session session;
   /** 接收userId */
   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<Object,Object> map = new HashMap<Object, Object>();
      	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());
      }

   /**

    * 收到客户端消息后调用的方法
      *
    * @param message 客户端发送过来的消息
    * @throws IOException 
    * @throws DocumentException 
      */
      @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);

      }


	/**
	 *
	 * @param session
	 * @param error
	 */
	@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'
				  })
				});
			}
  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值