JFinal使用WebSocket

2017-09-10  本文已影响154人  一一小知

1、先建立一个Maven项目,如果是老项目,也可转成maven项目,参见我之前写的一篇帮助:
Myeclipse普通java项目转maven项目

2、pom.xml引用相关jar包,1.7之后支持,配置如下:

    <dependencies>
<!--        <dependency>
            <groupId>javax.websocket</groupId>
            <artifactId>javax.websocket-api</artifactId>
            <version>1.1</version>
            <scope>provided</scope>
        </dependency> -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

tomcat7和jave EE 1.7都支持,注意引用一个,不要重复。

3、编写事件拦截处理代码:
ZhiWebSocketHandler.java

package com.yyxz.main;

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.handler.Handler;
import com.jfinal.kit.StrKit;

public class ZhiWebSocketHandler extends Handler {

    private Pattern filterUrlRegxPattern;
    
    public ZhiWebSocketHandler(String filterUrlRegx) {
        if (StrKit.isBlank(filterUrlRegx))
            throw new IllegalArgumentException("The para filterUrlRegx can not be blank.");
        filterUrlRegxPattern = Pattern.compile(filterUrlRegx);
    }
    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        // TODO Auto-generated method stub
        if (filterUrlRegxPattern.matcher(target).find())
            return ;
        else {
            next.handle(target, request, response, isHandled);
        }
    }

}

在JFinal Config中进行注册:

public class DemoConfig extends JFinalConfig {
//...
    public void configHandler(Handlers me) {
        me.add(new ContextPathHandler("ctx"));
        me.add(new ZhiWebSocketHandler("^/websocket"));
// 也可以使用UrlSkipHandler,就不用编写Handler处理类了
//      me.add(new UrlSkipHandler("^/websocket", false));
    }
//...
}

4、后台监听websocket代码:
WebSocketController.java

package com.yyxz.controller;

import java.io.IOException;

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

@ServerEndpoint("/websocket")
public class WebSocketController {
    public WebSocketController() {
        System.out.println(" WebSocket init~~~");
    }

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("onOpen");
    }

    @OnClose

    public void onClose(Session session) {
        System.out.println("onClose");
    }
    
//  @OnError
//  public void onError(Session session) {
//      System.out.println("onError");
//  }

    @OnMessage
    public void onMessage(String requestJson, Session session)
            throws IOException {
        requestJson = "一一小知回复:" + requestJson; 
        System.out.println(requestJson);
        session.getBasicRemote().sendText(requestJson);
    }
}

5、在前端发起,编写页面:
webSocketTest.jsp

<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- for HTML5 -->
<title>Java后端WebSocket的Tomcat实现</title>
</head>
<body>
    Welcome
    <br />
    <input id="text" type="text" />
    <button onclick="send()">发送消息</button>
    <hr />
    <button onclick="closeWebSocket()">关闭WebSocket连接</button>
    <hr />
    <div id="message"></div>
</body>

<script type="text/javascript">
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/yiyixiaozhi/websocket");
    }
    else {
        alert('当前浏览器 Not support websocket')
    }

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

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

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }

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

    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>

结果如下:

image.png image.png
上一篇下一篇

猜你喜欢

热点阅读