JFinal整合WebSocket,服务端给客户端发送消息

webSocket处理类

com.zr.platform.websocketjava.io.IOExceptionjava.util.Setjava.util.concurrent.CopyOnWriteArraySetjava.util.concurrent.atomic.AtomicIntegerjavax.websocket.javax.websocket.javax.websocket.javax.websocket.Sessionjavax.websocket.server.(=)
WebSocketController {
    String = AtomicInteger = AtomicInteger()Set<WebSocketController> = CopyOnWriteArraySet<>()String =Session () {
        = + .getAndIncrement()}

    (Session session) {
        .= session.add()System..println(+ session.getId())String message = String.()(message)}

    (Session session) {
        System..println(+ session.getId()).remove()String message = String.()(message)}

    (String messageSession session) {
        System..println(+message++session.getId())String response = String.(message)(response)}

    (String msg) {
        (WebSocketController client : ) {
            {
                (client) {
                    client..getBasicRemote().sendText(msg)}
            } (IOException e) {
                System..println().remove(client){
                    client..close()} (IOException e1) {
                    }
                String message = String.(client.)(message)}
        }
    }
}



需要新加一个Handler拦截websocket请求

com.zr.platform.websocketjava.util.regex.Patternjavax.servlet.http.HttpServletRequestjavax.servlet.http.HttpServletResponsecom.jfinal.handler.Handlercom.jfinal.kit.StrKitWebSocketHandler Handler{
    Pattern (String filterUrlRegx) {
        (StrKit.(filterUrlRegx))
            IllegalArgumentException()= Pattern.(filterUrlRegx)}
    (String targetHttpServletRequest requestHttpServletResponse response[] isHandled) {
        (.matcher(target).find())
            .handle(targetrequestresponseisHandled)}

}



在JFinal配置文件里配置 (MainConfig)

(Handlers me) {
me.add(WebSocketHandler())}



客户端页面

websocket = (in window){
                  websocket = WebSocket()}
          {
                 ()
              }

           websocket.= (){
              console.()}websocket.= (event){
                   console.()}

           websocket.= (event){
                  console.(event.data)}

          websocket.= (){
                   console.()}

           window.= (){
                   websocket.()}

           (innerHTML){
                   document.().+= innerHTML + }

          (){
                   websocket.()}

          (){
                  message = document.().valuewebsocket.(message)}


评论区

JFinal

2017-12-20 21:30

贴代码的时候可以点选一下编辑器的第二个叫做“代码语言”的下拉框,然后再贴进去,否则会出现代码丢失以及格式不正确的情况

感谢你的分享

热门分享

扫码入社