jfinal 整合websocket 的完整實現 java

場景爲用戶發送 信息到服務器,服務器接收後,智能回覆。用於聊天機器人。web

1.maven環境加包
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-websocket-api</artifactId>
<version>7.0.47</version>
<scope>provided</scope>
</dependency>apache

2.Jfinal 配置文件修改(DemoConfig extends JFinalConfig )api

public void configHandler(Handlers me) {
        //me.add(new ContextPathHandler("contextPath"));
        me.add(new WebSocketHandler("^/websocket")) 
    }tomcat

3.WebSocketHandler 文件
public class WebSocketHandler extends Handler{
private Pattern filterUrlRegxPattern;
    
    public WebSocketHandler(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) {
        if (filterUrlRegxPattern.matcher(target).find())
            return ;
        else
            next.handle(target, request, response, isHandled);
        
    }
}安全

4.接收信息發送信息服務器

@ServerEndpoint("/websocket")
public class WebSocketTest {
    public static CorpusService srv=CorpusService.me;
     //靜態變量,用來記錄當前在線鏈接數。
    private static AtomicInteger onlineCount = new AtomicInteger(0);websocket

    //concurrent包的線程安全Set,用來存放每一個客戶端對應的MyWebSocket對象。若要實現服務端與單一客戶端通訊的話,能夠使用Map來存放,其中Key能夠爲用戶標識
    //protected static CopyOnWriteArraySet<WebSocketTest> webSocketSet = new CopyOnWriteArraySet<WebSocketTest>();
    private static ConcurrentHashMap<String, WebSocketTest> webSocketSet = new ConcurrentHashMap<String, WebSocketTest>();
    //與某個客戶端的鏈接會話,須要經過它來給客戶端發送數據
    private Session session;session

    public WebSocketTest() {
        System.out.println(" WebSocket init~~~");
    }
    
    /**
     * 鏈接創建成功調用的方法
     * @param session  可選的參數。session爲與某個客戶端的鏈接會話,須要經過它來給客戶端發送數據
     */
    @OnOpen
    public void onOpen(Session session){
         System.out.println("新客人爲" + session.getId());
        this.session = session;
       // webSocketSet.add(this);     //加入set中
        webSocketSet.put(session.getId(), this);//加入map中
        addOnlineCount();           //在線數加1
        System.out.println("有新鏈接"+session.getId()+"加入!當前在線人數爲" + getOnlineCount());
    }socket

    /**
     * 鏈接關閉調用的方法
     */
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);  //從set中刪除
        subOnlineCount();           //在線數減1
        System.out.println("有一鏈接關閉!當前在線人數爲" + getOnlineCount());
    }maven

    /**
     * 收到客戶端消息後調用的方法
     * @param message 客戶端發送過來的消息
     * @param session 可選的參數
     * @throws IOException 
     * @throws InterruptedException 
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException, InterruptedException {
        System.out.println("來自客戶端的消息111:" + message);
        //羣發消息
        getMessage(message,session);
        //if (webSocketSet.get(session.getId()) != null) {
        //    webSocketSet.get(session.getId()).sendMessage("用戶" + session.getId() + "發來消息:" + "<br/> " + message);
        //}
        //session.getAsyncRemote().sendText("##"+message);
        //for(WebSocketTest item: webSocketSet){
         //   try {
         //       item.sendMessage(session.getId()+"說:"+message);
         //   } catch (IOException e) {
          //      e.printStackTrace();
          //      continue;
           // }
       // }
    }

    /**
     * 發生錯誤時調用
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("發生錯誤");
        error.printStackTrace();
    }

    /**
     * 這個方法與上面幾個方法不同。沒有用註解,是根據本身須要添加的方法。
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

    public static int getOnlineCount() {
        return onlineCount.get();
    }

    public static void addOnlineCount() {
        onlineCount.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineCount.decrementAndGet();
    }
    
    public void getMessage(String msg,Session session) throws InterruptedException{
     //獲取數據  

   AiCorpus cor=srv.getCorpus(msg);
        if(cor!=null){
            String msgs=cor.getMessage();
            String keywords=cor.getUsekeywords();
            if(msgs.contains("/r/n")){
                String[] strs=msgs.split("/r/n");
                for(String str :strs){
                    if (webSocketSet.get(session.getId()) != null &&!"".equals(str)) {
                        try {
                            webSocketSet.get(session.getId()).sendMessage(str);
                             Thread.sleep(500);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }else
            {
                if (webSocketSet.get(session.getId()) != null &&!"".equals(msgs)) {
                    try {
                        webSocketSet.get(session.getId()).sendMessage(msgs);
                         Thread.sleep(500);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            if (webSocketSet.get(session.getId()) != null &&!"".equals(keywords)) {
                try {
                    webSocketSet.get(session.getId()).sendMessage("-->"+keywords);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
        }else{
            try {
                webSocketSet.get(session.getId()).sendMessage("系統支持的詞語:贈險是什麼,保險是");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
}

5.測試工具:
http://coolaf.com/tool/chattest

6.請注意 默認jetty 環境不支持 websockt  ,本人親測 必在tomcat 8.5 下經過。

相關文章
相關標籤/搜索