ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

websocket

2021-04-13 21:59:10  阅读:132  来源: 互联网

标签:websocket WebSocket session import message public


 filter

package  com.dyh.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        System.out.println(req.getRequestURI());
        System.out.println(req.getSession().getId());
        filterChain.doFilter(servletRequest,
                servletResponse);
    }

    @Override
    public void destroy() {

    }
}

GetHttpSessionConfigurator

package com.dyh.websocket;

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;

public  class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator {
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        HttpSession httpSession=(HttpSession) request.getHttpSession();
        sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
    }
}

WebSocket

package com.dyh.websocket;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */

@ServerEndpoint(value = "/websocket", configurator = GetHttpSessionConfigurator.class)
public class WebSocketTest {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
    private static CopyOnWriteArraySet<WebSocketTest> webSocketSet = new CopyOnWriteArraySet<WebSocketTest>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    private HttpSession httpSession;

    /**
     * 连接建立成功调用的方法
     * @param session  可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session,EndpointConfig config){
        this.session = session;
        this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println("有新连接["+session.getId()+"]所在会话["+httpSession.getId()+"]加入!当前在线人数为" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
        //群发消息
        for(WebSocketTest item: webSocketSet){
            if(item==this || item.httpSession==this.httpSession) continue;
            try {
                item.sendMessage("<img src=1.png>"+  message);
            } catch (Exception e) {
                System.err.println(e.getMessage());
                continue;
            }
        }
    }

    /**
     * 发生错误时调用
     * @param session
     * @param error
     */
    @OnError
    public void one rror(Session session, Throwable error){
        System.err.println("发生错误");
        error.printStackTrace();
    }


    public void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

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

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

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

  index.jsp

<%@ page language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Java后端WebSocket的Tomcat实现</title>
  <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
  <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>
<body>
<div class="container">

  <div class="row clearfix">
    <div class="col-md-12 column">

      <div class="form-group" >
       <label  id="ts" style="color: red;"></label>
      </div>


    </div>
    <div class="col-md-12 column" id="message" style="height: 500px;overflow-y: scroll;border-bottom: 1px solid aquamarine;"  >
    </div>
  </div>

  <div class="row clearfix">

      <div class="col-md-12 column">

            <div class="form-group" >
              <textarea class="form-control" id="text" rows="4" ></textarea>
            </div>


      </div>
      <div class="col-md-12 column">
        <div class="form-group" >
          <button onclick="closeWebSocket()" class="btn btn-default">关闭WebSocket连接</button>
          <button onclick="openWebSocket()" class="btn btn-default">开启WebSocket连接</button>
          <button  onclick="send()" class="btn btn-default" style="float: right">发送消息</button>
        </div>
      </div>
  </div>
</div>



</body>

<script type="text/javascript">
  var websocket = null;


  function setWebSocketEvent(){
    //连接发生错误的回调方法
    websocket.onerror = function () {
      $("#ts").html("WebSocket连接发生错误");
    };

    //连接成功建立的回调方法
    websocket.onopen = function () {
      $("#ts").html("WebSocket连接成功");
    }

    //接收到消息的回调方法
    websocket.onmessage = function (e) {
      $('#message').append("<h4 style='text-align: right'>"  +e.data+"</h4>");
      setScrollForBottom();
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
      $("#ts").html("WebSocket连接关闭");
    }


  }


  //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接。
  window.onbeforeunload = function () {
    closeWebSocket();
  }
  function  closeWebSocket() {
    websocket.close();
  }


  function openWebSocket(){
    websocket = new  WebSocket("ws://localhost:8080/websocket");
    setWebSocketEvent();
  }

  //发送消息
  function send() {
      var message = $('#text').val();
      var s=message.split('\n')
      var smsg="";
      for(var i=0;i<s.length;i++){
        if(i+1==s.length)
          smsg=smsg+s[i];
        else
          smsg=smsg+s[i]+"<br>";
      }
      websocket.send(smsg);
  }

  function setScrollForBottom(){
    var height = document.getElementById("message").scrollHeight;
    $("#message").scrollTop(height);
    $("#message").scrollHeight;
  }

  $(function () {
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
      websocket = new  WebSocket("ws://localhost:8080/websocket");
      setWebSocketEvent()
    }
    else {
      $("#ts").html('当前浏览器 Not support websocket');
    }

  })

</script>
</html>

效果

标签:websocket,WebSocket,session,import,message,public
来源: https://blog.csdn.net/caststudy/article/details/115680100

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有