H5W3
当前位置:H5W3 > java > 正文

java Tomcat websocket无法正常工作

我尝试了如下的websocket示例代码,我的浏览器支持HTML 5 websocket,但是下面的示例代码始终在javascript中提示“关闭”。代码会怎样?

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 {
// 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>

当我连接到“http://localhost:8080/web_test/websocket”时,我得到了正确的消息,即“欢迎使用websocket 2”。我的index.jsp文件位于web_test之后的根目录中。因此,我的部署应该很好,但是哪里有问题。我只是想不通。

最佳答案

从您的servlet代码中注释或删除这两种方法,然后尝试正常运行Web套接字。如果这两种方法都存在于servlet中,则websocket将处于关闭状态

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 {
// TODO Auto-generated method stub
}

本文地址:H5W3 » java Tomcat websocket无法正常工作

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址