java聊天 如果不填被发送人则将数组全部发送

依赖

 
        
        org.springframework.boot
        spring-boot-starter-websocket
        

java
基本无改动 复制粘贴用

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.prevention.entity.AppChatrecordEntity;
import com.prevention.entity.AppStaffEntity;
import com.prevention.service.AppChatrecordService;
import com.prevention.service.AppStaffService;
import com.prevention.utils.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.concurrent.ConcurrentHashMap;

@ServerEndpoint("/imserver/{userId}")
@Component
public class WebSocketServer {
    private static AppStaffService appStaffService;
    private static AppChatrecordService appChatrecordService;
    private static WebSocketServer webSocketServer;
    @Autowired
    public void setAppData(AppStaffService appStaffService,AppChatrecordService appChatrecordService) {
        webSocketServer.appStaffService = appStaffService;
        webSocketServer.appChatrecordService = appChatrecordService;
    }

    private static Class a = WebSocketServer.class;
    /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private String userId="";
    private String uidhead="";
    private String uidname="";
    private String[] touserids;
    private String touserid="";
    private String content ="";
    private String type ="";

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen( Session session, @PathParam("userId") String userId) {
        this.type = type;
        this.session = session;
        this.userId= userId;//获取发送人id
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
            //加入set中
        }else{
            webSocketMap.put(userId,this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }

        Result.ok("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());
        AppStaffEntity entity=appStaffService.selectId(Integer.parseInt(userId));
        this.uidhead=entity.getStaffimg();//用户头像
        this.uidname=entity.getStaffname();//用户名
        try {
            sendMessage("{mag:'连接成功',uidhead:"+this.uidhead+",uidname:"+this.uidname+"}");
        } catch (IOException e) {
            Result.error("用户:"+userId+",网络异常!!!!!!");
        }
    }


    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        Result.ok("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("发送人:"+userId+",报文:"+message);

        JSONObject json = JSONObject.parseObject(message);
        touserid =json.getString("toUserId");;
        content = json.getString("contentText");

        Result.ok("用户消息:"+userId+",报文:"+message);

        //可以群发消息
        //消息保存到数据库、redis
        if(StringUtils.isNotBlank(message)){
            try {
                //解析发送的报文
                JSONObject jsonObject = JSON.parseObject(message);
                //追加发送人(防止串改)
                jsonObject.put("fromUserId", this.userId);
                String toUserId = jsonObject.getString("toUserId");//被发送用户
                String neirong = jsonObject.toJSONString();//发送的内容
                String contentText= jsonObject.getString("contentText");
                String type = jsonObject.getString("type");//发送的内容类型
                System.out.println(type);
                  //这里可以保存数据库
                  
                if (toUserId==null||"".equals(toUserId)) {
                    touserids=appStaffService.selectfalseId(userId);//获取了除自己以外所有人id 如果没填id时用;
                    sendInfo(neirong);//群发
                    //for (String touser : touserids)
                    //    fasong(touser, neirong);
                }
                else
                    fasong(toUserId,neirong);

            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }
    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) throws IOException {
        Enumeration ids = webSocketMap.keys();
        while (ids.hasMoreElements()) {
            webSocketMap.get(ids.nextElement()).sendMessage(message);
        }
    }
    /**
     * @Author 翎墨袅
     * @Description //TODO 发送消息
     * @Date 18:56 2020/5/27
     * @Param [error]
     * @return void
     **/
    public void fasong(String touid,String neirong) throws Exception{
        //传送给对应touid用户的websocket

        if(StringUtils.isNotBlank(touid)&&webSocketMap.containsKey(touid)){
            webSocketMap.get(touid).sendMessage(neirong);
        }else{
            Result.error("请求的userId:"+touid+"不在该服务器上");
            //否则不在这个服务器上,发送到mysql或者redis
        }
    }

    /**
     *
     * @param error
     */
    @OnError
    public void onError(Throwable error) {
        Result.error("用户错误:"+this.userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }


}

div




    
    websocket通讯




【userId】:

【toUserId】:

【toUserId】:

【操作】:

【操作】:

java聊天 如果不填被发送人则将数组全部发送_第1张图片
uniapp







你可能感兴趣的:(java聊天 如果不填被发送人则将数组全部发送)