websocket——Firefox 无法建立到 ws://... 服务器的连接

页面访问java websocket服务时,出现异常,Firefox下的异常是:Firefox 无法建立到 ws://... 服务器的连接;

IE下的异常是:WebSocket Error: Incorrect HTTP response. Status code 404, Not Found

环境是:apache-tomcat-7.0.62、jdk1.7.0_67、@ServerEndpoint("/websocket")这种声明式写法

我的排查步骤:

1、tomcat的JAVA_HOME指向jdk7

2、Firefox参数调整,据说默认是关闭websocket的,但是我的版本是38.0.6,没有关闭

3、web.xml头部改为xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

4、最后发现,是由于我引入了一个javax.websocket-api.jar放到了WEB-INF/lib/下面,可能跟tomcat7的websocket-api.jar有冲突。

去掉javax.websocket-api.jar后异常消失





Testing websocket


	

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/websocket")
public class WebSocketTest {

	@OnMessage
	public void onMessage(String message, Session session) throws IOException, InterruptedException{
		// Print the client message for testing purposes
	    System.out.println("Received: " + message);
	   
	    // Send the first message to the client
	    session.getBasicRemote().sendText("This is the first server message");
	   
	    // Send 3 messages to the client every 5 seconds
	    int sentMessages = 0;
	    while(sentMessages < 3){
	      Thread.sleep(5000);
	      session.getBasicRemote().sendText("This is an intermediate server message. Count: " + sentMessages);
	      sentMessages++;
	    }
	   
	    // Send a final message to the client
	    session.getBasicRemote().sendText("This is the last server message");
	}
	
	@OnOpen 
	public void onOpen(){
		System.out.println("Client connected");
	}
	
	@OnClose
	public void onClose(){
		System.out.println("Connection closed");
	}
	
}



你可能感兴趣的:(java,html)