我在grails中实现websocket服务器并且在客户端连接到它时遇到错误但仅在生产模式下。 这是我得到的错误:
WebSocket connection to 'ws://localhost:8080/myApp/websocketDoc' failed: Error during WebSocket handshake: Unexpected response code: 404
在开发模式下一切正常。
我的src / groovy中有一个课程
package myApp;
import java.util.HashMap;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.websocket.DeploymentException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerContainer;
import javax.websocket.server.ServerEndpoint;
import org.codehaus.groovy.grails.web.json.JSONObject;
import org.codehaus.groovy.grails.web.json.JSONArray;
import org.codehaus.groovy.grails.web.util.WebUtils;
import grails.util.Environment;
@WebListener
@ServerEndpoint("/websocketDoc")
public class WebsocketServletContextListener implements ServletContextListener {
private static final JSONArray jsonOpenedDocuments = new JSONArray();
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
final ServerContainer serverContainer = (ServerContainer) servletContextEvent.getServletContext()
.getAttribute("javax.websocket.server.ServerContainer");
try {
if (Environment.current == Environment.DEVELOPMENT) {
serverContainer.addEndpoint(WebsocketServletContextListener)
}
} catch (DeploymentException e) {
e.printStackTrace();
}
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
@OnOpen
public void handleOpen() {
System.out.println("Client is now connected.");
}
@OnMessage
public String handleMessage(String requestStr, Session userSession) {
return "msg";
}
@OnClose
public void handeClose(Session userSession) {
System.out.println("Client is now disconnected. id:" + userSession.id);
}
@OnError
public void handleError(Throwable t) {
t.printStackTrace();
}
}
在我的依赖项中,我有:BuilConfig.groovy:
dependencies {
runtime 'mysql:mysql-connector-java:5.1.22'
compile 'c3p0:c3p0:0.9.1.2'
bundle('javax.websocket:javax.websocket-api:1.1') {
export = false
}
}
要将监听器添加到web.xml,我在/ scripts中有以下脚本:
import groovy.xml.StreamingMarkupBuilder
eventWebXmlEnd = {String tmpfile ->
def root = new XmlSlurper().parse(webXmlFile)
root.appendNode {
'listener' {
'listener-class' (
'myApp.WebsocketServletContextListener'
)
}
}
webXmlFile.text = new StreamingMarkupBuilder().bind {
mkp.declareNamespace(
"": "http://java.sun.com/xml/ns/javaee")
mkp.yield(root)
}
}
在客户端,我收到以下行中的错误:
var webSocketUrl = "${createLink(uri: '/websocketDoc', absolute: true).replaceFirst(/https/, /wss/).replaceFirst(/http/, /ws/)}";
var webSocket = new WebSocket(webSocketUrl); // getting 404 error when running in production mode
任何线索为什么这只适用于开发模式? 感谢