WebSocket connection was unsuccessful. Switching to Comet and resending the request

I have been utilizing the Atmosphere framework 2.0.0.RC5 to expand my web application with websocket capabilities and encountered a perplexing error 'Websocket failed. Downgrading to Comet and resending' that I can't seem to resolve.

To start off, I referenced a websocket chat example: https://github.com/Atmosphere/atmosphere-samples/tree/master/samples/websocket-chat

The setup consists of an html+js client and a Java backend.

Backend

  • Tomcat 7.0.42 with NIO protocol enabled
  • Web module v3.0 with Spring and Atmosphere servlets
  • Custom CORS filter to allow atmosphere headers
  • Logging every received message on the server side

(extra code excluded)

public void onTextMessage(WebSocket webSocket, String message) throws IOException {
    logger.info("Message received: " + message);
    webSocket.broadcast(mapper.writeValueAsString(mapper.readValue(message, Data.class)));
}

Client

index.html

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="js/lib/jquery.atmosphere-2.0.2.js"></script>
<script type="text/javascript" src="js/aimpl.js"></script>

aimpl.js

$(function() {
    "use strict";
    var socket = $.atmosphere;

    var request = {
        url: 'http://localhost:8181/services/echo',
        transport: "websocket",
        contentType: "application/json",
        //connectTimeout: '300000',
        fallbackTransport: 'long-polling',
        enableXDR: true,
        logLevel: 'debug'
    };

    request.onMessage = function (response) {
        console.log(response.responseBody)
    };

    request.onOpen = function(response) {
        console.log('Atmosphere connected using ' + response.transport);
    };

    request.onReconnect = function (request, response) {
        console.log("reconnecting...");
    };

    request.onError = function(response) {
        console.log('an error has occured.');
    };

    var channel = socket.subscribe(request);
    channel.push(JSON.stringify({ author: 'me', message: 'hello from websocket!' }));
});

Upon opening 'index.html', I encounter an error in the console (jquery.atmosphere-2.0.2.js line 1097) and no messages are being logged on the server:

Interestingly, it functions when I manually type directly into the console:

The messages get logged by the server, so I am assuming the server side is functioning correctly:

I suspect it may be a JavaScript problem, though I'm not completely certain. I have tried adjusting the connectTimeout parameter without success. Any insights as to why it's not working within the script?

Answer №1

Relocate the channel.push code within the onOpen function.

The error occurs when attempting to transmit data prior to establishing the connection. Additional information can be found here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Choosing a button value from a form in Selenium: Best practices

I am looking to streamline the process of registering for classes. The snippet of HTML code on the page appears as follows: <form id="SearchClasses" name="selectedStatusForm" action="/more/SearchClasses.action" method=&quo ...

When calling a Vue.js method, it appears to be undefined

Currently, I'm working on developing a Chrome extension using Vue and Browserify. Within my component file, I'm attempting to invoke a method called animateBackground from the mounted hook. However, when checking the console, an error message is ...

Guide on creating a dynamic Cucumber-Selenium framework without relying on Static WebDriver instances

Currently, I am exploring different methods to improve my web app testing approach with the Cucumber+Selenium framework. In my current setup, I have been using static instances of the webdriver class across all page/hooks classes. However, I am aware that ...

Invoking AngularJS Function from Login Callback Script

Just getting started with angularjs and I have a logincallback function that is used for external login. This function returns the returnUrl, closes the externallogin pop up, and redirects back to the main page. function loginCallback(success, returnUrl) ...

@ManyToMany multiple instances

I am facing an issue with persistence in my code. The Meal class contains a list of Products, and the Product class has a list of Meals defined in a @ManyToMany relation. When I attempt to save the data, the Compiler tries to save every product, resulting ...

Encountering an issue while trying to verify user registration in MySQL using Node.js Express. During the user registration process, an error arises indicating that 'res' is not defined

import React from 'react' import { Link } from 'react-router-dom' import {useNavigate} from 'react-router-dom'; import { useState } from 'react' axios from "axios" const Register = () => { const [i ...

Redux state assigns object to another object

I started with an initial state that looks like this: let initialState = { items: [ { name: 'a' }, { name: 'b' } ], otherItems: [] } I am attempting to copy the items array and assign i ...

Guide to creating the onclick feature for a dynamic button in Meteor

<template name="actionTemplate"> {{#each action}} <button class="myButton" id={{_id}}>btn</button> {{> action}} {{/each}} </template> <template name="action"> <div class="sct" id={{_id}}> ...

Iterating over objects within a nested array using ng-repeat

My back-end is sending me an array of string arrays (Java - CXF-RS). The length of each array within the string arrays ranges from 1 to n. In order to display this data on my front-end, I am utilizing ng-repeat. Everything is functioning correctly with o ...

Choose a particular iFrame that contains numerous occurrences of identical names

Currently, I am facing an issue with the 3 iFrames specified on the page I'm working with. Here are their details: <iframe class="col-51" height="560" src="https://attendee.gototraining.com/embed/886b2/catalog/40xxxx bgColor=ffffff" frameborder="0 ...

Issue with Panel Settings and Tooltip in Amcharts

Looking for solutions to two specific issues that I am struggling with: I have two charts with multiple panels, each having only one scroll bar. My problem lies with the balloon text - when hovering over a balloon, I need to display two different texts ...

What is the best way to include and delete several images on a canvas?

Recently, I've started working with canvas in HTML5 and I'm tasked with creating a paint application. One of the features I need to implement is the ability to dynamically add selected images to the canvas as the mouse moves, and then have the fu ...

Is it necessary for me to master React in order to code with React Native?

As I move on to learning React and/or React Native after mastering Angular, it feels like a natural progression in my development journey. My understanding is that React Native could streamline the process of building Android/iOS native apps within one pr ...

The backbone view is having trouble processing the data from this.model.toJSON()

I've been working on a Backbone code implementation to display all modifications before adding data to my model. However, every time I try to add something from my form, my view returns "this.model.toJSON() is not a function" and I can't figure o ...

What causes let to lose significance within the context of React development?

In my React code snippet, I am encountering an issue with the organizationId variable. Even though I can see its value in the first and second instances, I am unable to see it in the third instance. This strange behavior is occurring in a Next.js based pro ...

The error message `org.openqa.selenium.StaleElementReferenceException: element is not attached to the page document while navigating a List` indicates that the

Can someone help me troubleshoot this error that keeps popping up? I need assistance fixing it. The website I'm currently working on is: "". While navigating through this site, the following code snippet generates an error: List<WebElement> cl ...

Function for swapping out the alert message

I am searching for a way to create my own custom alert without interfering with the rendering or state of components that are currently using the default window.alert(). Currently working with React 15.x. function injectDialogComponent(message: string){ ...

Upgrade your Angular 2 application by swapping out the Java socket client for the socket.io client

I have been successfully connecting to a server and sending a message using Java client socket. Now, I am attempting to achieve the same functionality using socket.io in my Angular 2 application. I have tried the code below but have had no success in sendi ...

Customize React JS Material UI's InputBase to be responsive

https://i.stack.imgur.com/9iHM1.gif Link: codesandbox Upon reaching a certain threshold, like on mobile devices, the elements inside should stack vertically instead of horizontally, taking up full length individually. How can this be achieved? ...

Prevent XHR from responding to OPTIONS method

Currently, I am in the process of developing an API that will be hosted on Azure functions and a Web App that will reside on Azure Blob storage. To ensure seamless communication between my API and the users' browsers, I have implemented proper handlin ...