【问题标题】:Websocket connection fails on google compute engine instance谷歌计算引擎实例上的 Websocket 连接失败
【发布时间】:2017-04-11 11:37:34
【问题描述】:

我正在测试一个使用 javascript websocket 连接的聊天服务应用程序(javascript 和 java)。在我自己的机器上一切正常。我在我的 Google 计算引擎 (GCE) 实例上部署了该应用程序。当我尝试使用聊天服务时,连接失败(错误代码:1006)。我会在下面贴出相关代码

websocket连接的javascript代码是

            var server;
            try {
                server = new WebSocket('ws://' + window.location.host +
                        '<c:url value="/chat/${chatSessionId}" />');
                server.binaryType = 'arraybuffer';
            } catch(error) {
                modalErrorBody.text(error);
                modalError.modal('show'); 
                return;
            }

            server.onerror = function(event) {
                modalErrorBody.text(event.data);
                modalError.modal('show');
            };

我尝试了以下替代方法

  1. 将window.location.host替换为实例的实际外部IP地址(下***)

server = new WebSocket('ws://***.***.**.*' + '&lt;c:url value="/chat/${chatSessionId}" /&gt;');

  1. 在外部 IP 地址后添加端口号

server = new WebSocket('ws://***.***.**.*:80' + '&lt;c:url value="/chat/${chatSessionId}" /&gt;');

这些都不起作用。相同的错误信息(错误代码:1006)

这里是java部分的代码:

@ServerEndpoint(value = "/chat/{sessionId}",
        encoders = ChatMessageCodec.class,
        decoders = ChatMessageCodec.class,
        configurator = ChatEndpoint.EndpointConfigurator.class)
@WebListener
public class ChatEndpoint implements HttpSessionListener
{
    private static final String HTTP_SESSION_PROPERTY = "com.wrox.ws.HTTP_SESSION";
    private static final String WS_SESSION_PROPERTY = "com.wrox.http.WS_SESSION";
    private static long sessionIdSequence = 1L;
    private static final Object sessionIdSequenceLock = new Object();
    private static final Map<Long, ChatSession> chatSessions = new Hashtable<>();
    private static final Map<Session, ChatSession> sessions = new Hashtable<>();
    private static final Map<Session, HttpSession> httpSessions =
            new Hashtable<>();
    public static final List<ChatSession> pendingSessions = new ArrayList<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("sessionId") long sessionId)
    {
        ...
    }
    @OnMessage
    ...
    @OnClose
    ...
}

【问题讨论】:

    标签: javascript java websocket google-compute-engine


    【解决方案1】:

    我发现在tomcat的server.xml中,以下部分被注释掉了导致问题的地方

    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 2014-08-21
      • 2015-08-06
      • 1970-01-01
      • 2019-02-26
      相关资源
      最近更新 更多