美文网首页
2018.08.22 WebSocket 点对点 发送消息

2018.08.22 WebSocket 点对点 发送消息

作者: 薛定谔的猴子 | 来源:发表于2018-08-22 16:34 被阅读95次

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

  • 依赖包

        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.2</version>
        </dependency>
  • 数据结构包装类

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<String, WebSocket> users = new ConcurrentHashMap<String, WebSocket>();
    private Session session;

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


    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        Map<String, List<String>> 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<String> 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" %>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <style type="text/css">
        body {
            width: 1200px;
        }
    </style>
</head>
<body>
<div>
    <hr>
    您的姓名:<input type="text" id="username">
    <hr>
    <button onclick="build()">建立连接</button>
</div>
<hr>
<div>
    发送给:<input type="text" id="tousername">
</div>
<hr>
<div>
    <textarea rows="10" cols="100" id="content">
    </textarea>
    <br> <br>
    <button onclick="send()">发送</button>
</div>

<div id="showMessage"></div>
<script>
    var websocket = null;

    function build() {
        var username = $("#username").val();
        if ('WebSocket' in window) {
            websocket = new WebSocket(
                "ws://localhost:18080/websocket?username=" + username);
            //连接成功建立的回调方法
            websocket.onopen = function () {
                $("#showMessage").append("<p color='red'>build success!</p>");
                $("#tousername").append("<option>" + username + "</option>");
            }
            //连接发生错误的回调方法
            websocket.onerror = function () {
                alert("登录失败");
            };
            //连接关闭的回调方法
            websocket.onclose = function () {
                $("#showMessage").html("连接关闭");
            };
            //接收到消息的回调方法
            websocket.onmessage = function (e) {
                var jsonObject = JSON.parse(e.data);
                $("#showMessage").append("<p>" + jsonObject.from + "对" + jsonObject.to + "说:" + jsonObject.content + "</p>");
            };
        } else
            alert("Not Support!");
    }

    window.onbeforeunload = function () {
        if (null != websocket)
            websocket.close();
    };

    function send() {
        var username = $("#username").val();
        var content = $("#content").val();
        var tousername = $("#tousername").val();
        var mes = {
            "from": username,
            "to": tousername,
            "content": content
        };
        if (null != websocket)
            websocket.send(JSON.stringify(mes));
    }
</script>
</body>
</html>

界面如下

相关文章

网友评论

      本文标题:2018.08.22 WebSocket 点对点 发送消息

      本文链接:https://www.haomeiwen.com/subject/yreyiftx.html