要配置Tomcat以支持WebSocket協議,需要做以下幾個步驟:
<Connector port="8080" protocol="org.apache.coyote.http11.Http11NioProtocol"
connectionTimeout="20000"
redirectPort="8443" />
<servlet>
<servlet-name>WebSocketServlet</servlet-name>
<servlet-class>com.example.WebSocketServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WebSocketServlet</servlet-name>
<url-pattern>/websocket</url-pattern>
</servlet-mapping>
var webSocket = new WebSocket("ws://localhost:8080/yourAppName/websocket");
webSocket.onmessage = function(event) {
console.log("Received message: " + event.data);
};
這樣就完成了Tomcat的WebSocket配置,可以通過WebSocket協議與Tomcat服務器進行雙向通信。