最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - Tomcat websocket is not working - Stack Overflow

programmeradmin1浏览0评论

I have tried a websocket sample code as below, my browser is supporting HTML 5 websocket, but the sample code below always prompt "Close" in the javascript. What happen 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("wele to websocket 2");
            response.getWriter().flush();   
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    @Override
    protected StreamInbound createWebSocketInbound(String arg0,
            HttpServletRequest arg1) {

        return new TheWebSocket();
    }

    private class TheWebSocket extends MessageInbound
    {
        private WsOutbound outbound;

        @Override
        public void onOpen( WsOutbound outbound )
        {
            this.outbound = outbound;
             System.out.println("socket opened!");
        }

        @Override
        public void onTextMessage( CharBuffer buffer ) throws IOException
        {
            try
            {
                    outbound.writeTextMessage( CharBuffer.wrap( "abc testing".toCharArray() ) );
                    System.out.println("Message sent from server.");
            }
            catch ( IOException ioException )
            {
                    System.out.println("error opening websocket");
            }

        }

        @Override
        protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
            // TODO Auto-generated method stub

        }
    }

}

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 got correct message which is "wele to websocket 2". And my index.jsp file is in the root directory after web_test. So, my deployment should be fine, but somewhere is wrong. I just cannot figure it out.

I have tried a websocket sample code as below, my browser is supporting HTML 5 websocket, but the sample code below always prompt "Close" in the javascript. What happen 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("wele to websocket 2");
            response.getWriter().flush();   
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    @Override
    protected StreamInbound createWebSocketInbound(String arg0,
            HttpServletRequest arg1) {

        return new TheWebSocket();
    }

    private class TheWebSocket extends MessageInbound
    {
        private WsOutbound outbound;

        @Override
        public void onOpen( WsOutbound outbound )
        {
            this.outbound = outbound;
             System.out.println("socket opened!");
        }

        @Override
        public void onTextMessage( CharBuffer buffer ) throws IOException
        {
            try
            {
                    outbound.writeTextMessage( CharBuffer.wrap( "abc testing".toCharArray() ) );
                    System.out.println("Message sent from server.");
            }
            catch ( IOException ioException )
            {
                    System.out.println("error opening websocket");
            }

        }

        @Override
        protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
            // TODO Auto-generated method stub

        }
    }

}

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 got correct message which is "wele to websocket 2". And my index.jsp file is in the root directory after web_test. So, my deployment should be fine, but somewhere is wrong. I just cannot figure it out.

Share Improve this question asked Sep 12, 2012 at 6:09 Sam YCSam YC 11.7k22 gold badges111 silver badges163 bronze badges 6
  • I am using Apache Tomcat 7 and Chrome to establish WebSocket. But i ended up with getting error "Unexpected response code: 200 ". Any idea? What server you're using to establish handshake? – iamjustcoder Commented Oct 12, 2012 at 5:24
  • @gviswanathan Maybe you can post out your code, I am using Tomcat 7 too because only tomcat 7 (lower version does not) support websocket. My code above should work fine, plus the answer below. You should be able to get your websocket running. – Sam YC Commented Oct 12, 2012 at 6:29
  • I am using Tomcat 7.0.27. Will this version supports websocket? – iamjustcoder Commented Oct 12, 2012 at 8:05
  • @gviswanathan I think this version should support (the version that I use is 7.0.27), is easy to know that if it does not support, your pilation will not succeed. – Sam YC Commented Oct 12, 2012 at 14:47
  • Yes, WebSocketServlet is not available in 7.0.27 – iamjustcoder Commented Oct 15, 2012 at 8:55
 |  Show 1 more ment

1 Answer 1

Reset to default 6

Comment or remove these two methods from your servlet code and then try web sockets working fine.If these two present in the servlet , websocket is going to close state

protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().println("wele to websocket 2");
        response.getWriter().flush();
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }
发布评论

评论列表(0)

  1. 暂无评论