Having trouble receiving a response from the websocket using RxJS in Node.js with Angular

Currently experimenting with setting up a WebSocket using rxjs webSocket

I have managed to create a node server without any errors, but it is not sending messages to the server or connected users

When I switch to 'ws://echo.websocket.org/', I can see messages echoed back to me, however, there is no communication between users subscribed to the websocket in other open browsers

All I need is a straightforward method to exchange basic information among users

index.js

var express = require('express');


var WebSocketServer = require('websocket').server;

var app2 = express()//There is already another app var for main app server
var server2 = http.createServer(app2);
var server2 = app2.listen(8081, function () {
  console.log((new Date()) + ' Server is listening on port 8081');
})


  wsServer = new WebSocketServer({
  httpServer: server2,
  autoAcceptConnections: false
});

function originIsAllowed(origin) {

  if (origin === 'http://localhost:1234'){
    return true;

  }
// Add logic here to determine if the specified origin is permitted.

}

wsServer.on('request', function(request) {

  if (!originIsAllowed(request.origin)) {
    // Ensure that requests are only accepted from an allowed origin
    request.reject();
    console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
    return;
  }

  var connection = request.accept(null, request.origin);
  console.log((new Date()) + ' Connection accepted.');
  connection.on('message', function(message) {
    // console.log(message)
      if (message.type === 'utf8') {
          console.log('Received Message from: ' + connection.remoteAddress);
          connection.sendUTF(message.utf8Data);
      }
      else if (message.type === 'binary') {
          console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
          connection.sendBytes(message.binaryData);
      }
  });
  connection.on('close', function(reasonCode, description) {
      console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
  });
});

in my clientside socket service:

import { Injectable } from '@angular/core';
import { Observable } from '../../../node_modules/rxjs';

@Injectable()
export class SocketService {
  socket$ = Observable.webSocket( 'ws://localhost:8081');
  
  constructor() {
      this.connectToSocket()
   }

  connectToSocket(){
    this.socket$.subscribe(
      (message) => console.log('message received: ' + message),
      (err) => console.log(err),
      () => console.log('complete')
    );
  }


}

To send a message from another component, I use:

this.socketService.socket$.next(JSON.stringify('test'))

Answer №1

Based on the information provided in the WebSocket-Node documentation (https://github.com/theturtle32/WebSocket-Node/blob/master/docs/WebSocketServer.md), it is necessary to manually accept each connection before proceeding with the handshake.

Alternatively, you can enable the autoAcceptConnections feature in your server configuration by setting it to true, as shown below:

const wss = new WebSocketServer({ httpServer: server2, autoAcceptConnections: true });

If there are specific requirements for request checking, you have the option to use either accept or reject within your request handler like so:

request.accept('chosen-protocol', 'accepted-origin') 

or

request.reject()

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

What sets apart exporting a component from importing its module in another module?

When working with Angular, consider having both module A and module B. If I intend to utilize "A-component" within components of module B, what is the distinction between importing module A in Module B compared to including the "A-component" in the exports ...

"Enhancing User Experience with Angular 2: Customizing Component Selection and Sty

I am currently working on an Angular application that fetches a configuration file in .json format. My goal is to dynamically choose components and apply inline styles to them. Below is an example of the structure of the configuration data obtained from a ...

Whoops! The input buffer seems to be containing an image format that is not supported while attempting to utilize Next JS next-opt

I initially used the default Image Optimization component in my Next JS app, only to realize that the site could only be hosted on Vercel and not on other web hosting platforms. This limitation prompted me to explore the next-optimized-images package, whic ...

What is the best way to retrieve data from an array within an Express application?

Working with the rest API using express ejs in Node.js has brought up an issue. The JSON data received from the API contains an array within an array. Specifically, I am trying to extract the value of the feature_image attribute under guid. However, when ...

Converting string patterns to regular expressions

I am utilizing mongodb to store data. My requirement is to save complete regular expressions as strings: { permissions: [{ resName: '/user[1-5]/ig', isRegex: true }] } Although I am aware of the existence of the module mongoose-rege ...

Implementing Angular - Injecting a component dynamically into another component

Currently, I am working on developing a small UI components framework for my personal use and enjoyment. One of the components I'm working on is a Tab component. To test this component, I need to dynamically inject another component (TabContainerCompo ...

Encountering the PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR when the database transitions to an Idle state

Outside of regular operating hours, the database transitions into an Idle state. To re-establish connection to the data, I am using the code snippet below, var mysql = require('mysql'); var settings = require('./config.js'); var conne ...

Perform a JSON POST request from an HTML script to a Node.JS application hosted on a different domain

In an attempt to send string data via a post json request using JavaScript within an .erb.html file, I am facing the challenge of sending it to a node.js app on another domain that uses express to handle incoming requests. After researching online, I have ...

Having trouble attaching handlers to a socket within a loop. Frustrating :/

In order to handle events sent to a socket in a more organized way, I have implemented a router. Within this router, my goal was to assign each module to a specific event. I mapped out event strings and their respective handlers within the "handlers" objec ...

The Fusion of Ember.js and Socket.io: Revolutionizing Web

I have been trying to incorporate a basic Ember application into the view of my node application. I have verified that Ember is properly set up and my sockets are functioning correctly. However, I am encountering an issue where the data is not being displa ...

What is the best way to merge three collections without using $unwind and generate a nested outcome depending on a specific condition?

People Database: [ { "_id": ObjectId("5f3258cfbaaccedaa5dd2c96"), "gender": "male", "name": { "title": "mr", "first": "victor", " ...

Assigning a Value to a Dropdown Menu in Angular

I have some JSON data that contains a True/False value. Depending on whether it is true or false, I want a specific option in a Select Dropdown to be automatically selected. This is the HTML code using Angular 16: <select name="reportNo" id=& ...

`Common issues when running NPM INSTALL in a Vue project`

I purchased a template and tried to install it on my PC, but I encountered an issue with the dependencies. When I run the NPM INSTALL command, I receive an error related to Python 2. About a year ago, I installed the template without any problems. However ...

What exactly is the role of HTTP in data flow? Is JSON separate from the HTTP requests?

Let's take a look at this code snippet that demonstrates how to fetch a list of to-dos from an SQLite3 database: First, there is an axios request in the frontend: useEffect(() => { axios.get('http://localhost:3001/todo', {}) .the ...

I'm struggling to get the Bootstrap collapse navbar-collapse feature to work in my Angular

My attempt at implementing the bootstrap collapse navbar-collapse feature in my Angular 8 project seems to be not working correctly after compilation. I have already installed: bootstrap - 4.3.1 and made changes to the angular.json file. I also have jquery ...

What is the method for obtaining the PATH environment variable separator in Node.js?

When using Python, I can achieve the following: import os os.pathsep ===> ':' for unix, ';' for windows. How can I do this in Node.js? Currently, I am checking if the platform is win32 or not process.platform === 'win32 ...

Accessing form data within Mongoose schema hooks via JavaScript

I have a form where I've split the content into two separate MongoDB schemas. I want to access variables that are within node.js/express.js directly in mongoose schema hooks, whether through pre or post hooks of the schema. Here are my files: expres ...

Is it possible to integrate ngx-translate with database-supported translations?

I am managing a vast database (pouchDB) that stores translations, with each language having its own dedicated database. How can I leverage ngx-translate to easily access these translations directly from the database? ...

There seems to be a problem with the bundle.js file caused by Uglify

I've just finished a project and now I'm ready to start building it. Utilizing a boilerplate project, I still find myself struggling to comprehend all the npm/webpack intricacies happening behind the scenes. Whenever I try to run "npm start", I k ...

Dynamically generating PWA manifests in Angular 7

I just finished building a Progressive Web App (PWA) using Angular 6. Now, I am looking to customize the icons and start URLs dynamically because the app will be accessed through different URLs, each with its own unique logo assigned to it. Is there a way ...