java - 远程无法连接tomcat java websocket,但本地可以

标签 java websocket

在 Tomcat 7.0.54 上本地部署应用程序,然后连接到 ws://localhost:8080/request/subscription/messenger/xxxx 时 一切都很好。

但是当在远程服务器上部署为 .war 时(Tomcat 8.0.18 - websocket-api.jar 位于 lib 文件夹中)无法连接,可以说 ws://myshost.com:8080/request/subscription/messenger/xxxx

FireBug 中的 FF 输出“无法建立与服务器的连接” “网络错误:404 未找到 - http://myshost.com:8080/request/subscription/messenger/xxxx

JS ws-client 代码:

            var webSocket;
            var messages = document.getElementById("messages");
            var token = document.getElementById("token").value;
//            var tokenTo = document.getElementById("token_to").value;
            var subscrContext = document.getElementById("context").value;
            var host = document.getElementById("host").value;
//            var port = document.getElementById("port").value;

            function openSocket(){
                // Ensures only one connection is open at a time
                if(webSocket !== undefined && webSocket.readyState !== WebSocket.CLOSED){
                    writeResponse("WebSocket is already opened.");
                    return;
                }
                // Create a new instance of the websocket
                var wsUrl = "ws://"+host+":8080/request/subscription/"+subscrContext+"/"+token;
                console.log(wsUrl);
                webSocket = new WebSocket(wsUrl);

                /**
                 * Binds functions to the listeners for the websocket.
                 */
                webSocket.onopen = function(event){
                    // For reasons I can't determine, onopen gets called twice
                    // and the first time event.data is undefined.
                    // Leave a comment if you know the answer.
                    if(event.data === undefined) 
                        return;

                    writeResponse(event.data);
                };

                webSocket.onmessage = function(event){
//                  var json = JSON.parse(event.data);
                    writeResponse(event.data);
                };

                webSocket.onclose = function(event){
                    writeResponse(event.data);
                };
            }

            /**
             * Sends the value of the text input to the server
             */
            function send(){
                var text = document.getElementById("messageinput").value;
//                var json = {
//                  'action':'send_message', 
//                  'uid':123,
//                  'text':text
//                };
                webSocket.send(text);
            }

            function closeSocket(){
                webSocket.close();
            }

            function writeResponse(text){
                messages.innerHTML += "<br/>" + text;
            }

            function clear() {
              messages.innerHTML = '';
            }           

Java ws-server-endpoint 代码

@ServerEndpoint(value = "/subscription/{context}/{token}", encoders = {MessageEncoder.class}, decoders = {MessageDecoder.class})
public class SubscriptionServer implements Commons {

  private Queries q;

//  private ByteBuffer buff;

  private int currentUserId;

  private static final int           
          ERR_REQ_PARAM = 802;

  // storing sessions for messenger
  public static Map<Integer, Session> usersMessenger = new HashMap<>(),
  // storing sessions for road
  usersRoad = new HashMap<>();

  public static Map<Integer, List<Integer>> userPosts = new HashMap<>();

  private static final Map<Integer, String> 
          errUserMsg = new HashMap<>(), 
          errSysMsg = new HashMap<>();

  private String token;

  private final static String 
          CONTEXT_MESSENGER = "messenger", 
          CONTEXT_ROAD = "road";

  @OnOpen
  public void onOpen(@PathParam("context") String context,
          @PathParam("token") String grossToken, Session sess) throws IOException,
          ClassNotFoundException, SQLException, EncodeException, JSONException {

    token = Helper.getToken(grossToken);
    currentUserId = Helper.getUserId(grossToken);    

    Logger.log("open user: "+currentUserId);

//    sess.getBasicRemote().sendObject(
//            new JSONObject().put("token", token).put("uid", currentUserId));

    q = new Queries();

    if (q.checkToken(token, currentUserId) > 0) {

      subscribeUser(currentUserId, sess, context);

      sess.getBasicRemote().sendObject(new JSONObject()
              .put("token", token).put("user_id", currentUserId));
    } else {
      sess.getBasicRemote().sendObject(Helper.getErrorMessage(ERR_TOKEN, 
              "Этот аккаунт используется с другого устройства.", "Этот аккаунт используется с другого устройства."));
      sess.close();      
    }

//    System.out.println("User with id: " + sess.getId() + " has been connected!");

  }

  @OnMessage
  public void onMessage(@PathParam("context") String context, JSONObject json, Session sess) throws IOException, JSONException, EncodeException {

//    System.out.println("User with sid: "+sess.getId()+" sending msg:"+json.getString("text"));
//    JSONObject json = new JSONObject(msg);
//    Logger.log(json.toString());
//    sess.getBasicRemote().sendText("Received message:"+json);

    // ping - pong 
    if (json.has("ping") && json.getInt("ping")==1) {
      sess.getBasicRemote().sendObject(new JSONObject().put("pong", 1));
      return;
    }

    switch (context) {
      case CONTEXT_MESSENGER:
        sendMessageEvent(json.getInt("user_id"), json, sess);
        break;
      case CONTEXT_ROAD:
        sendRoadEvents(currentUserId, json, sess);
        break;
    }

//    String message = "Received message int bytes: "+msg;
//    
//    byte[] bytes = message.getBytes("UTF-16BE");
//    
//    buff = ByteBuffer.allocate(bytes.length+1);
//    
//    buff.put(bytes);
//    
//    sess.getBasicRemote().sendBinary(buff);
  }

  @OnClose
  public void onClose(Session sess, CloseReason reason, @PathParam("context") String context)
          throws IOException, JSONException, EncodeException {
    unsubscribeUser(currentUserId, context);
    sess.getBasicRemote().sendObject(Helper.getSuccess(new JSONObject().put("reason", "ServerEndpoint timeout")));
  }

  private void subscribeUser(int userId, Session sess, String context) {

    Logger.log("subscribe user: "+userId);

    SubscriptionQueries subscrQueries = new SubscriptionQueries();

    try {
      // check tmp memory table - send if contains some      
      List<String> jsonList = subscrQueries.getSubscriptionTmp(userId);

      if (!jsonList.isEmpty()) {
        sess.getBasicRemote().sendObject(new JSONObject().put("success", jsonList));
      }

      switch (context) {
        case CONTEXT_MESSENGER:
          usersMessenger.put(userId, sess);
          sess.getBasicRemote().sendObject(Helper.getSuccess());
          break;
        case CONTEXT_ROAD:
          usersRoad.put(userId, sess);
//          int startIndex = (request.getParameter("start_index") == null) ? 0 : Integer.parseInt(request.getParameter("start_index"));
//          int quantity = (request.getParameter("quantity") == null) ? 20 : Integer.parseInt(request.getParameter("quantity"));
          // last 20 posts user sees when open road
          int startIndex = 0;
          int quantity = 20;
          List<Integer> posts = subscrQueries.getUserPosts(startIndex, quantity);
          userPosts.put(userId, posts);
          sess.getBasicRemote().sendObject(Helper.getSuccess());
          break;
      }

    } catch (ClassNotFoundException | SQLException | IOException | JSONException | EncodeException ex) {
      Logger.log(Arrays.toString(ex.getStackTrace()), "error.log");
      Logger.log(ex.getMessage(), "error.log");
    }

  }

  private void unsubscribeUser(int userId, String context) throws JSONException, IOException, EncodeException {

    Session sess;

    switch (context) {
      case CONTEXT_MESSENGER:
        sess = usersMessenger.remove(userId);
        sess.getBasicRemote().sendObject(Helper.getSuccess());
        break;
      case CONTEXT_ROAD:
        sess = usersRoad.remove(userId);
        userPosts.remove(userId);
        sess.getBasicRemote().sendObject(Helper.getSuccess());
        break;
    }
  }

  private void sendMessageEvent(int userId, JSONObject json, Session sess) throws IOException, EncodeException, JSONException {

    if (usersMessenger.containsKey(userId)) {

      Session userSess = usersMessenger.get(userId);
      userSess.getBasicRemote().sendObject(json);

    } else { // tmp memory tbl in DB
      SubscriptionQueries subscrQueries = new SubscriptionQueries();
      try {
        subscrQueries.setSubscriptionTmp(userId, json.toString());
      } catch (ClassNotFoundException | SQLException ex) {
        Logger.log(Arrays.toString(ex.getStackTrace()), "error.log");
        Logger.log(ex.getMessage(), "error.log");
      }
    }

    sess.getBasicRemote().sendObject(Helper.getSuccess());

  }

  private void sendRoadEvents(int currentUserId, JSONObject json, Session sess) throws JSONException, IOException, EncodeException {
    // send to all users online, that where subscribed on these (say 20 last) posts
    // likes, comments, deletes, comment responses
    int userId;
    Session userSess;

    if (json.isNull("post_id")) {
      sess.getBasicRemote().sendObject(Helper.getErrorMessage(ERR_REQ_PARAM, 
              "Нет обязательного параметра post_id", "Нет обязательного параметра post_id"));
      return;
    }

//    sess.getBasicRemote().sendObject(new JSONObject().put("User Roads: ", usersRoad));
//    
//    sess.getBasicRemote().sendObject(new JSONObject().put("Users posts: ", userPosts));   

      for (Entry<Integer, Session> user : usersRoad.entrySet()) {

        userId = user.getKey();
        userSess = user.getValue();

        // ensure - not equals to this user 
        if (currentUserId != userId && userPosts.containsKey(userId)) {

          List<Integer> posts = userPosts.get(userId);

          sess.getBasicRemote().sendObject(new JSONObject().put("Users posts: ", posts));

          if (!posts.isEmpty() && posts.contains(json.getInt("post_id"))) {

            userSess.getBasicRemote().sendObject(json);

          }

        }

      }
      // success after all
      sess.getBasicRemote().sendObject(Helper.getSuccess());

  }

  private void setErrors() {

    errSysMsg.put(ERR_REQ_PARAM, "Нет обязательного параметра");
    errUserMsg.put(ERR_REQ_PARAM, "Нет обязательного параметра");

  }

}

服务器正在 100% 运行 - 使用 web.xml 中定义的 Servlet 对其他上下文的 http 请求进行了多次检查 - 一切都是标准的,每个请求都正常工作。

最佳答案

答案既聪明又简单:

1) 扩展 HttpServlet

2) 重写 doGet 方法以接收带参数的 GET

需要获取 WebSocket 握手和升级 header 。

PS,但在本地主机上,没有 HttpServlet 和 doGet 也可以正常工作,因为它是同一台机器,并且在本地主机上打开的套接字服务器(例如在端口 8080 上)不需要通过 http 握手,这件事很难确定 - 我希望这对某人有帮助。

关于java - 远程无法连接tomcat java websocket,但本地可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28384000/

相关文章:

java - 当客户端更改 IP 地址或断开连接时,是否热衷于捕获 websocket-close 事件?

node.js - WebSocket 连接建立错误:net::ERR_CONNECTION_CLOSED

c++ - 不向 socket.io nodejs(服务器)发送数据 socket.io c++(客户端)

java - jsoup:解析特定标签之后的特定标签的数据

java - 如何通过IP地址与另一台机器连接?

java - 在运行时跳过 TestNg 测试

websocket - SockJS 增加池大小

javascript - Nodejs、Express 和 WebSockets : Relaying a message to all clients other than the sender

java - 如何在 Java 15 以后继续使用 Javascript

java - 迁移到 64 位后 JVM 崩溃