175. Spring Boot WebSocket: Single Chat

 

【Video & Communication Platform】

à SpringBoot Video 

http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=400000000155061&utm_medium=share

à  SpringCloud Video

http://study.163.com/course/introduction.htm?courseId=1004638001&utm_campaign=commission&utm_source=400000000155061&utm_medium=share

à Spring Boot source code 

https://gitee.com/happyangellxq520/spring-boot

à Spring Boot communication platform 

http://412887952-qq-com.iteye.com/blog/2321532

 

Origin of need:

       In the previous article, group chat has been implemented, and here is a brief introduction to order chat. Here , the id in session.getId() is used as the only message channel (here we call it the channel number of communication), session.getId() is an incrementing number, starting from 0 and incrementing by 1, 2, 3... Actually This id will not be used as an identifier, it is just for the convenience of explanation.

Show results:

Let's take a look at the final effect, as shown below:

 

Goku News:



 

 

 

Master message:



 

 

 

Bajie news:



 

1. Server adjustment

1.1  Create a Socket message object SocketMsg

       Here we can't use simple text messages to send messages, we use json to send messages. So you need to create a message object first, which contains the message sender, message receiver, message type (single chat or group chat), or just a message, as follows:

com.kfit.socket.SocketMsg

package com.kfit.socket;
 
public class SocketMsg {
       private int type;//Chat type 0: group chat, 1: single chat.
       private String fromUser;//Sender.
       private String toUser;//接受者.
       private String msg;//消息
       public int getType() {
              return type;
       }
       public void setType(inttype) {
              this.type = type;
       }
       public String getFromUser() {
              return fromUser;
       }
       public void setFromUser(String fromUser) {
              this.fromUser = fromUser;
       }
       public String getToUser() {
              returntoUser;
       }
       public void setToUser(String toUser) {
              this.toUser = toUser;
       }
       public String getMsg() {
              returnmsg;
       }
       public void setMsg(String msg) {
              this.msg = msg;
       }
}

 

 

1.2  调整建立连接的方法(MyWebSocket

       这里主要是要使用一个map对象保存频道号和session之前的关系,之后就可以通过频道号获取session,然后使用session进行消息的发送。

定义一个map对象:

//用来记录sessionId和该session进行绑定 
 private static Map<String,Session> map = new HashMap<String, Session>(); 

 

 

修改连接的方法onOpen

       在建立连接的时候,就保存频道号(这里使用的是session.getId()作为频道号)和session之间的对应关系:

    @OnOpen
    public void onOpen(Session session,@PathParam("nickname") String nickname) {
        this.session = session;
        this.nickname = nickname;
        map.put(session.getId(), session);
       
        webSocketSet.add(this);     //加入set中
        System.out.println("有新连接加入!当前在线人数为" + webSocketSet.size());
        this.session.getAsyncRemote().sendText(this.nickname+"上线了"+"(他的频道号是"+session.getId()+")");
    }

 

 

修改消息发送的方法 onMessage

       从客户端传过来的数据是json数据,所以这里使用jackson进行转换为SocketMsg对象,然后通过socketMsgtype进行判断是单聊还是群聊,进行相应的处理:

@OnMessage
    public void onMessage(String message, Session session,@PathParam("nickname") String nickname) {
        System.out.println("来自客户端的消息:" + message);
 
        ObjectMapper objectMapper = new ObjectMapper();
        SocketMsg socketMsg;
              try {
                     socketMsg = objectMapper.readValue(message, SocketMsg.class);
                     if(socketMsg.getType() == 1){
                            //单聊.需要找到发送者和接受者.
                           
                            socketMsg.setFromUser(session.getId());//发送者.
                            Session fromSession = map.get(socketMsg.getFromUser());
                            Session toSession = map.get(socketMsg.getToUser());
                            //发送给接受者.
                            if(toSession != null){
                                   //发送给发送者.
                                   fromSession.getAsyncRemote().sendText(nickname+":"+socketMsg.getMsg());
                                   toSession.getAsyncRemote().sendText(nickname+":"+socketMsg.getMsg());
                            }else{
                                   //发送给发送者.
                                   fromSession.getAsyncRemote().sendText("系统消息:对方不在线或者您输入的频道号不对");
                            }
                     }else{
                            //群发消息
                      broadcast(nickname,socketMsg);
                     }
              } catch (JsonParseException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              } catch (JsonMappingException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
    }

 

 

二、客户端调整

2.1 加入频道号输入框

       提供用户输入频道号进行单聊:

消息:<input id="text" type="text" />
频道号<input id="toUser" type="text" />
<button onclick="send()">发送消息</button>

 

 

2.2 修改消息发送方法

       这里使用了js对象进行消息的传递,这里使用JSON.stringifyjson对象转换为json字符串,如下代码:

//发送消息
       function send() {
              //获取输入的文本信息进行发送
              var message = document.getElementById('text').value;
              var toUser = document.getElementById('toUser').value;
              var socketMsg = {msg:message,toUser:toUser};
              if(toUser == ''){
                     //群聊.
                     socketMsg.type = 0;
              }else{
                     //单聊.
                     socketMsg.type = 1;
              }
             
              websocket.send(JSON.stringify(socketMsg));
       }

 

       好了,到这里就可以实现了单聊+群聊的效果。

 

三、新问题的提出

       上面虽然可以实现单聊的方式,但是在具体的实际场景中,想要知道对方的频道号好像不是那么容易的哦,那么这个要怎么解决呢?大家在玩QQ群的时候,应该都用过聊天界面中的右边的群成员吧,对头,就是要实现一个在线群成员列表的功能,这样用户在操作的时候就可以直接通过点击某个在线的用户进行聊天了。博主,你会实现嘛?^_^,博主还暂时没有这个计划,其实看懂了上面的代码之后,要实现在线群成员列表也不是很难的事情了。

 

 

四、源代码

 

       最后奉上源代码。大家可以下载源代码玩玩!

访问地址:https://gitee.com/happyangellxq520/spring-boot 找到spring-boot-websocket-2017,直接下载即可运行。

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326492334&siteId=291194637