2012-08-26 134 views
2

我想在tomcat 7.0.29上使用websocket來實現pub/sub系統,但不知怎的,我不知道爲什麼,它只是總是提醒「關閉」每次我打開瀏覽器.. ENV是Tomcat的7.0.29,Eclipse的朱諾,用Scala編寫.. 大加讚賞,如果任何人都可以幫助...tomcat websocket:無法連接到tomcat服務器

我的servlet低於:

[PubServlet]:

class PubServlet extends WebSocketServlet { 
override def createWebSocketInbound (subProtocol: String, request: HttpServletRequest): StreamInbound = { 
     println("create#############################################") 
     new WebSocketHandler() 
    } 
} 

[InitServlet]:

public class InitServlet extends HttpServlet { 

    private static final long serialVersionUID = -3163557381361759907L; 

    private static List<MessageInbound> socketList; 

    public void init(ServletConfig config) throws ServletException { 
     InitServlet.socketList = new ArrayList<MessageInbound>(); 
     super.init(config); 
     System.out.println("Server start============"); 
    } 

    public static synchronized List<MessageInbound> getSocketList() { 
     return InitServlet.socketList; 
    } 
} 

[WebsocketHandler]:

class WebSocketHandler extends MessageInbound{ 

    protected override def onBinaryMessage(arg0: ByteBuffer) { 
     // TODO Auto-generated method stub 

    } 
    protected override def onTextMessage(msg: CharBuffer) { 

    } 

    protected override def onClose(status: Int) { 
     println(status) 
     super.onClose(status) 
    } 

    protected override def onOpen(outbound: WsOutbound) { 
     super.onOpen(outbound) 
     InitServlet.getSocketList().add(this) 
    } 
} 

和我的客戶端代碼是在這裏:

<%@ 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/PubSub_Web/index.do"); 
     alert(ws); 
    } 
    else if ('MozWebSocket' in window) 
     ws = new MozWebSocket("ws://localhost:8080/PubSub_Web/index.do"); 
    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> 

回答

0

this answer。您最好使用標準jaxax websocket-api,它可在Tomcat 7.0.47

0

您需要重寫getReadTimeout方法,該方法用於以毫秒爲單位設置套接字超時。例如,如果您要設置套接字超時2分鐘(2 * 60 * 1000),則可能會使用下面的代碼。

@Override 
public int getReadTimeout() { 
    return 2*60*1000; 
} 

注意:您可以通過返回-1來設置無限(始終打開)。