Java Websocket 示例不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20092563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Websocket example won't work
提问by Nyger
I try run this example:
我尝试运行这个例子:
import java.util.logging.Level;
import java.util.logging.Logger;
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(value = "/chat")
public class ChatServer {
private static final Logger LOGGER =
Logger.getLogger(ChatServer.class.getName());
@OnOpen
public void onOpen(Session session) {
LOGGER.log(Level.INFO, "New connection with client: {0}",
session.getId());
}
@OnMessage
public String onMessage(String message, Session session) {
LOGGER.log(Level.INFO, "New message from Client [{0}]: {1}",
new Object[] {session.getId(), message});
return "Server received [" + message + "]";
}
@OnClose
public void onClose(Session session) {
LOGGER.log(Level.INFO, "Close connection for client: {0}",
session.getId());
}
@OnError
public void onError(Throwable exception, Session session) {
LOGGER.log(Level.INFO, "Error for client: {0}", session.getId());
}
}
I use Tomcat 7.0.47
, I check link: ws://localhost/Tests/chat
.
Do I need register this websocket or add some things in web.xml
?
Any idea why is not working for me?
我使用Tomcat 7.0.47
,我检查链接:ws://localhost/Tests/chat
。我需要注册这个 websocket 或添加一些东西web.xml
吗?知道为什么不适合我吗?
回答by samael
I had the same problem trying to use WebSocket API on Tomcat 7.0.47. The error message being displayed client side wasn't any help at all and my server side endpoint was never being created.
我在尝试在 Tomcat 7.0.47 上使用 WebSocket API 时遇到了同样的问题。客户端显示的错误消息根本没有任何帮助,我的服务器端端点从未被创建。
After much wasted time I found it was due to way I had set the dependency for javax.websocket-api
. I'm using Maven which has the default scope as compile
which causes problems as Tomcat has the websocket-api.jar
in its lib folder. Setting the dependency to provided
solved it.
在浪费了很多时间之后,我发现这是由于我为javax.websocket-api
. 我正在使用具有默认范围的 Maven,compile
这会导致问题,因为 Tomcatwebsocket-api.jar
在其 lib 文件夹中有 。设置依赖来provided
解决它。
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
Hope this helps
希望这可以帮助
It's also worth noting that if running behind Apache you will need mod_proxy_wstunnel
and if using IIS you will need version 8.0 as anything prior does not support websockets.
还值得注意的是,如果在 Apache 后面运行,您将需要mod_proxy_wstunnel
,如果使用 IIS,您将需要 8.0 版,因为以前的任何东西都不支持 websockets。