Websocket:TomCat7 與 TomCat8的區別

weixin_34007291發表於2018-03-26

這兩天因為專案需求研究了一下Websocket,發現TomCat7與TomCat8還是有些區別的,總的來說TomCat8比較簡單,易實現。
網上有很多文章都指出TomCat7需要修改web.xml以及單獨匯入.jar包,但是我沒有修改任何地方,也能連線成功。

  • 區別:
    1、tomcat7需要建立一個連結類來繼承WebSocketServlet,但是tomcat8不需要
    2、tomcat使用@WebServlet("/DemoWebSocket")建立URL對映,而tomcat8使用@ServerEndpoint("/DemoWebSocket")
  • 相同點:
    1、jsp程式碼不需要變
    2、連結地址不變
    程式碼是借鑑別人的
  • 貼上tomcat7下的程式碼
package com.scoket.scoketTest;

import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import com.scoket.scoketTest.HelloMessageInbound;

@WebServlet("/DemoWebSocket")
public class WebSocketTest extends WebSocketServlet {

    private static final long serialVersionUID = 1L; 
    private final AtomicInteger connectionIds = new AtomicInteger(0);
    @Override
    protected StreamInbound createWebSocketInbound(String arg0,
            HttpServletRequest arg1) {
        // TODO Auto-generated method stub
        return new HelloMessageInbound(connectionIds.getAndIncrement(), arg1 
                .getSession().getId()); 
    }

}

package com.socket;

import java.io.IOException; 
import java.io.InputStream; 
import java.io.Reader; 
import java.nio.CharBuffer; 
import org.apache.catalina.websocket.StreamInbound; 
import org.apache.catalina.websocket.WsOutbound; 

public class HelloMessageInbound extends StreamInbound {
    private String WS_NAME; 
    private final String FORMAT = "%s : %s"; 
    private final String PREFIX = "ws_"; 
    private String sessionId = ""; 
     
    public HelloMessageInbound(int id, String _sessionId) { 
          this.WS_NAME = PREFIX + id; 
          this.sessionId = _sessionId; 
         }
    
    @Override
     protected void onTextData(Reader reader) throws IOException { 
      char[] chArr = new char[1024]; 
      int len = reader.read(chArr); 
      send(String.copyValueOf(chArr, 0, len)); 
     } 
      
     @Override
     protected void onClose(int status) { 
      System.out.println(String.format(FORMAT, WS_NAME, "closing ......")); 
      super.onClose(status); 
     } 
      
     @Override
     protected void onOpen(WsOutbound outbound) { 
      super.onOpen(outbound); 
      try { 
       send("hello, my name is " + WS_NAME); 
       send("session id = " + this.sessionId); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
      
     private void send(String message) throws IOException { 
      message = String.format(FORMAT, WS_NAME, message); // 推送訊息
      System.out.println(message); 
      getWsOutbound().writeTextMessage(CharBuffer.wrap(message)); 
     } 
      
     @Override
     protected void onBinaryData(InputStream arg0) throws IOException { 
     }

}

前端jsp

<!DOCTYPE HTML> 
<html> 
<head> 
<title>tomcat7test</title> 
<style> 
body {padding: 40px;}
#outputPanel {margin: 10px;padding:10px;background: #eee;border: 1px solid #000;min-height: 300px;} 
</style> 
</head> 
<body> 
<input type="text" id="messagebox" size="60" /> 
<input type="button" id="buttonSend" value="Send Message" /> 
<input type="button" id="buttonConnect" value="Connect to server" /> 
<input type="button" id="buttonClose" value="Disconnect" /> 
<br> 
<% out.println("Session ID = " + session.getId()); %> 
<div id="outputPanel"></div> 
</body> 
<script type="text/javascript"> 
 var infoPanel = document.getElementById('outputPanel'); // 輸出結果皮膚 
 var textBox = document.getElementById('messagebox'); // 訊息輸入框 
 var sendButton = document.getElementById('buttonSend'); // 傳送訊息按鈕 
 var connButton = document.getElementById('buttonConnect');// 建立連線按鈕 
 var discButton = document.getElementById('buttonClose');// 斷開連線按鈕 
 // 控制檯輸出物件 
 var console = {log : function(text) {infoPanel.innerHTML += text + "<br>";}}; 
 // WebSocket演示物件 
 var demo = { 
  socket : null, // WebSocket連線物件 
  host : '',  // WebSocket連線 url 
  connect : function() { // 連線伺服器 
   window.WebSocket = window.WebSocket || window.MozWebSocket; 
   if (!window.WebSocket) { // 檢測瀏覽器支援 
    console.log('Error: WebSocket is not supported .'); 
    return; 
   } 
   this.socket = new WebSocket(this.host); // 建立連線並註冊響應函式 
   this.socket.onopen = function(){console.log("websocket is opened .");}; 
   this.socket.onmessage = function(message) {console.log(message.data);}; 
   this.socket.onclose = function(){ 
    console.log("websocket is closed ."); 
    demo.socket = null; // 清理 
   }; 
  }, 
  send : function(message) { // 傳送訊息方法 
   if (this.socket) { 
    this.socket.send(message); 
    return true; 
   } 
   console.log('please connect to the server first !!!'); 
   return false; 
  } 
 }; 
 // 初始化WebSocket連線 url 
 //demo.host=(window.location.protocol == 'http:') ? 'ws://' : 'wss://' ;
 //demo.host += window.location.host + '/tomcat7test/DemoWebSocket';
 demo.host = 'ws://localhost:9090/tomcat7test/DemoWebSocket'
 console.log(demo.host);
 // 初始化按鈕點選事件函式 
 sendButton.onclick = function() { 
  var message = textBox.value; 
  if (!message) return; 
  if (!demo.send(message)) return; 
  textBox.value = ''; 
 }; 
 connButton.onclick = function() { 
  if (!demo.socket) demo.connect(); 
  else console.log('websocket already exists .'); 
 }; 
 discButton.onclick = function() { 
  if (demo.socket) demo.socket.close(); 
  else console.log('websocket is not found .'); 
 }; 
</script> 
</html>
  • jar截圖


    1869411-c6a47e7633c4f33a.png
    jar截圖

相關文章