I tried the websocket sample code as shown below, my browser supports HTML 5 websocket, but the sample code below always asks for "Close" in javascript. What happens to the code?
websocket.java
@WebServlet("/websocket") public class websocket extends WebSocketServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().println("welcome to websocket 2"); response.getWriter().flush(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Index</title> <script type="text/javascript"> var ws = null; function startWebSocket() { if ('WebSocket' in window) ws = new WebSocket("ws://localhost:8080/web_test/websocket"); else if ('MozWebSocket' in window) ws = new MozWebSocket("ws://localhost:8080/web_test/websocket"); else alert("not support"); ws.onmessage = function(evt) { alert(evt.data); }; ws.onclose = function(evt) { alert("close"); }; ws.onopen = function(evt) { alert("open"); }; } function sendMsg() { ws.send(document.getElementById('writeMsg').value); } </script> </head> <body onload="startWebSocket();"> <input type="text" id="writeMsg"></input> <input type="button" value="send" onclick="sendMsg()"></input> </body> </html>
When I connect to "http: // localhost: 8080 / web_test / websocket", I received the correct message, which is "welcome to websocket 2". And the index.jsp file is in the root directory after web_test. So, my deployment should be fine, but somewhere wrong. I just can't understand.
GMsoF source share