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 onError(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>
效果