2018.08.22 WebSocket 点对点 发送消息

项目下载链接:https://pan.baidu.com/s/1VflXwPD6Pc2QQtRlzIyPQw 密码:n3f3

  • 依赖包

        
            javax
            javaee-api
            7.0
            provided
        
        
        
            com.google.code.gson
            gson
            2.8.2
        
  • 数据结构包装类

public class MessageDto {

    public String from;
    public String to;
    public String content;

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
  • ServerEndpoint

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.google.gson.Gson;


@ServerEndpoint("/websocket")
public class WebSocket {
    private String username;
    private static ConcurrentMap users = new ConcurrentHashMap();
    private Session session;

    private void sendMessage(String mes) {
        this.session.getAsyncRemote().sendText(mes);
    }


    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        Map> map = session.getRequestParameterMap();
        username = map.get("username").get(0);//url中携带的参数
        users.put(username, this);
    }

    @OnClose
    public void onClose() {
        users.remove(username);
    }

    @OnMessage

    public void onMessage(String message, Session session) {

        System.out.println("来自客户端的消息:" + message);

        Gson gson = new Gson();

        MessageDto mes = gson.fromJson(message, MessageDto.class);

        if (mes.getTo() == null) {

            Set key = users.keySet();

            for (String k : key) {

                if (k.equals(mes.from)) continue;

                users.get(k).sendMessage(message);

            }

        } else {

            WebSocket toServlet = users.get(mes.getFrom());

            WebSocket toServlet2 = users.get(mes.getTo());

            if (null != toServlet) {

                toServlet.sendMessage(message);

                toServlet2.sendMessage(message);

            }

        }
    }
}
  • 前端页面index.jsp

<%@ page language="java" pageEncoding="UTF-8" %>



    
    Insert title here
    
    



您的姓名:

发送给:



界面如下

你可能感兴趣的:(2018.08.22 WebSocket 点对点 发送消息)