下面是我为websocket尝试的例子,
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/socket")
public class ExampleWebSocket {
private static Queue<Session> queue = new ConcurrentLinkedQueue<Session>();
@OnMessage
public void onMessage(Session session, String msg) {
try {
System.out.println("received msg "+msg+" from "+session.getId());
ExecutorService executorService = Executors
.newFixedThreadPool(1);
ThreadClass newThread = new ThreadClass(session); // a thread class which is going to perform async operations
Future<String> fut = executorService.submit(newThread);
int i =10;
while(fut.isDone()){
if(i > 50){
fut.cancel(true);
return;
}
Thread.sleep(1000);
i++;
}
executorService.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
@OnOpen
public void open(Session session) {
queue.add(session);
System.out.println("New session opened: "+session.getId());
}
@OnError
public void error(Session session, Throwable t) {
queue.remove(session);
System.err.println("Error on session "+session.getId());
}
@OnClose
public void closedConnection(Session session) throws IOException {
queue.remove(session);
System.out.println("session closed: "+session.getId());
}
}
我在jar中添加了以下依赖项,
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
</dependency>
对于这个例子,当我试图从浏览器点击时,我总是得到404。 我们的项目也在3.2版本中运行。我是否必须在任何xml文件中添加此类配置,例如we.xml。我完全被困在这里。
此外,我尝试在javax.websocket-api的依赖项中添加<scope>provided</scope>
,然后部署失败,找不到类。
答案 0 :(得分:0)
较低版本的服务器不支持Websocket。 RUL下面提供了websocket支持的Web服务器列表。 https://github.com/Atmosphere/atmosphere/wiki/Supported-WebServers-and-Browsers