【SpringBoot +小程序】实现webSocket即时会话功能源码《一对一、一对多》

踩坑点:

   使用域名建立websocket连接报404,但使用ip地址连接成功,经尝试需:1、该域名已经备案成功;2、指定端口(ws://**.*.*:82/*****)

微信小程序端:

//建立连接
 wx.connectSocket({
       url: 'ws://localhost:82/insight/websocket/' + getApp().globalData.myopenId.openid
  /*  修改参数为"All" 则可对所有人发送消息  */
});
//连接成功
wx.onSocketOpen(function (res) {
        console.log("连接服务器成功。");
         getApp().globalData.socketOpen= true;
});

//接受数据
wx.onSocketMessage(function (res) {
      console.log("传入的原数据:");
      console.log(res);
})

//发送数据
wx.sendSocketMessage({
        data: JSON.stringify(msg)
})

Java端:

1、maven引入

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
/**
*引入spring-boot-starter-websocket就已经引入了
*    spring-boot-starter-web和spring-boot-starter,所以不要重复
*
/

 2、WebSocketStompConfig.java

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

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

}

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/websocket/{username}")
public class WebSocket {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 在线人数
     */

    public static int onlineNumber = 0;

    /**
     * 以用户的姓名为key,WebSocket为对象保存起来
     */
    private static Map<String,WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
    /**
     * 会话
     */
    private Session session;
    /**
     * 用户名称
     */
    private String username;
    /**
     * 建立连接
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) {
        onlineNumber++;
        logger.info("现在来连接的客户id:"+session.getId()+"用户名:"+username);
        this.username = username;
        this.session = session;
        logger.info("有新连接加入! 当前在线人数" + onlineNumber);
        try {
            //messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
            //先给所有人发送通知,说我上线了
            Map<String,Object> map1 = new HashMap<String,Object>();
            map1.put("messageType",1);
            map1.put("username",username);
            sendMessageAll(JSON.toJSONString(map1),username);

            //把自己的信息加入到map当中去
            clients.put(username, this);

            //给自己发一条消息:告诉自己现在都有谁在线
            Map<String,Object> map2 = new HashMap<String,Object>();
            map2.put("messageType",3);

            //移除掉自己
            Set<String> set = clients.keySet();
            map2.put("onlineUsers",set);
            sendMessageTo(JSON.toJSONString(map2),username);
        }
        catch (IOException e){
            logger.info(username+"上线的时候通知所有人发生了错误");
        }
    }
    @OnError
    public void onError(Session session, Throwable error) {
        logger.info("服务端发生了错误"+error.getMessage());
        //error.printStackTrace();
    }
    /**     * 连接关闭     */
    @OnClose
    public void onClose()    {
        onlineNumber--;
        //webSockets.remove(this);
        clients.remove(username);
        try {
            //messageType 1代表上线 2代表下线 3代表在线名单  4代表普通消息
            Map<String,Object> map1 = new HashMap<String,Object>();
            map1.put("messageType",2);
            map1.put("onlineUsers",clients.keySet());
            map1.put("username",username);
            sendMessageAll(JSON.toJSONString(map1),username);
        }catch (IOException e){
            logger.info(username+"下线的时候通知所有人发生了错误");
        }
        logger.info("有连接关闭! 当前在线人数" + onlineNumber);
    }
    /**

     * 收到客户端的消息

     *

     * @param message 消息

     * @param session 会话

     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            logger.info("来自客户端消息:" + message + "客户端的id是:" + session.getId());
            JSONObject jsonObject = JSON.parseObject(message);
            String textMessage = jsonObject.getString("message");
            String fromusername = jsonObject.getString("username");
            String tousername = jsonObject.getString("to");
            String touserPhoto = jsonObject.getString("touserPhoto");
            //如果不是发给所有,那么就发给某一个人

            //messageType 1代表上线 2代表下线 3代表在线名单  4代表普通消息

            Map<String, Object> map1 = new HashMap<String,Object>();
            map1.put("messageType", 4);

            map1.put("textMessage", textMessage);
            map1.put("fromusername", fromusername);
            map1.put("touserPhoto",touserPhoto);

            if (tousername.equals("All")) {
                map1.put("tousername", "所有人");

                sendMessageAll(JSON.toJSONString(map1), fromusername);

            } else {

                map1.put("tousername", tousername);

                sendMessageTo(JSON.toJSONString(map1), tousername);

            }
        } catch (Exception e) {

            logger.info("发生了错误了");

        }
    }
    public void sendMessageTo(String message, String ToUserName) throws IOException {

        for (WebSocket item : clients.values()) {
            if (item.username.equals(ToUserName) ) {

                item.session.getAsyncRemote().sendText(message);
                /**
                 *  getBasicRemote()  阻塞式 同步
                 *  getAsyncRemote() 非阻塞式 异步
                 */

                break;

            }
        }

    }
    public void sendMessageAll(String message,String FromUserName) throws IOException {

        for (WebSocket item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);

        }

    }
    public static synchronized int getOnlineCount() {

        return onlineNumber;

    }
}

猜你喜欢

转载自blog.csdn.net/qq_35808136/article/details/89451927