Cant get connection with Socket.IO from Angular to NodeJS - javascript

I am trying to solve this for hours.. if someone can help me.
I cant understand why this doenst emit or receive the message.
At angular I got this error:
http://localhost:4200/socket.io/?EIO=3&transport=polling&t=NEhK-JT 404
4200 is the PORT of my Angular Application and 8080 from my server.
NodeJS:
// Define Porta
const port = process.env.PORT || 8080;
var server = app.listen(port, function () {
console.log('Server Online - ' + port);
});
// Socket.io
var io = require('socket.io').listen(server);
io.on('connect', function (socket) {
console.log(`${socket.id} is connected`);
socket.on('room', function (room) {
console.log('room', room)
socket.join(room);
});
});
Angular 9:
import * as io from 'socket.io-client'
public socket
public orgId: string = '123abc'
ngOnInit(): void {
this.setupSocketConnection();
}
chat(nome: string, avatar: number, mensagem: string) {
io.connect(this.orgId).emit('organizacao', {
nome: nome,
mensagem: mensagem,
avatar: avatar,
});
}
setupSocketConnection() {
this.socket = io.connect(`http://localhost:8080`, {
reconnectionDelay: 1000,
reconnection: true,
reconnectionAttempts: 10,
transports: ['websocket'],
agent: false,
upgrade: false,
rejectUnauthorized: false
});
}
From my Console.log at Server
zEnR7Cp23zcur4_kAAAH is connected
86sIiMA8vRZEN-WcAAAI is connected
SU4K2n9jAx_UO2ndAAAJ is connected
UAwlMpNiZWhw_eo9AAAK is connected
K6myruVum4FPKTeLAAAL is connected
Z5QULdZtdsRo5gC1AAAM is connected

If you are trying to implement rooms then please read https://socket.io/docs/rooms/
For your case what I can see here is that on server-side you are listening to the event named room and on client-side you are emitting to organizacao and also you need to use the socket object instead of io, refer from here https://www.npmjs.com/package/socket.io-client
socket.connect(this.orgId).emit('room', {
nome: nome,
mensagem: mensagem,
avatar: avatar,
});

Related

Angular Node | SocketIO | Event not emitted from node

I had asked this question before but here's a simple code for the same.
Im sending the data to Node from angular via websocket but I don't get the emitted event:
I've followed 10+ tutorials and forums, newest from here: https://www.youtube.com/watch?v=66T2A2dvplY&t=317s
service:
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { io } from 'socket.io-client';
#Injectable({
providedIn: 'root'
})
export class SocketService {
socket = io('ws://localhost:3000'); // adding 'http://localhost:3000' also doesnt work
constructor() {}
listen(eventName: string) {
return new Observable( subscriber => {
this.socket.on(eventName, data => {
subscriber.next(data);
});
});
}
emit(eventName: string, data) {
this.socket.emit(eventName, data);
}
}
from component's ngOnInit(), this is called:
this._socketService.listen('test event').subscribe( data => {
console.log("data from server: ", data);
});
server code of Node:
const app = require('./app');
const port = process.env.PORT || 3000;
const server = require('http').createServer(app);
const socketio = require('socket.io');
const io = socketio(server,
{
serveClient: true,
pingInterval: 60000,
pingTimeout: 60000000,
cors: {
origin: "http://localhost:4200",
methods: ["GET", "POST"],
credentials: true
}
});
io.on('connection', function (socket) {
console.log("A user connected ", socket.connected); // works till here for every ping interval
socket.emit('test event', 'here is some data'); // this is either not executed or doesn't work
});
server.listen(port);
socket.connected is always true in NODE server, but false in Angular
What Ive tried:
CORS has been suppressed, I hope that's not the issue cuz nothing is seen like so
changing io.('connection' ...) to io.connect('connect'...)
init this.socket = io(...) in constructor
There is no data exchange seen in Network or Network > WS tab in case I emit from Angular too
This is my 3rd day with this problem, I'll highly appreciate any help.
Thank you
your mixing protocols from client.
change
socket = io('ws://localhost:3000');
to
socket = io('http://localhost:3000', { withCredentials: true });
As mentioned in introduction under chapter What Socket.IO is not that socket.io is not a pure WS lib.

How to connect AWS elasticache redis from Node.js application?

How to connect AWS elasticache redis from Node.js application ?
You're connecting to Redis. The fact that it's a managed AWS service is not really that important in this respect.
So, use a Node.js package that implements a Redis client interface, for example:
redis
node-redis
You can use the package ioredis
and stablish a connection like this
const Redis = require('ioredis')
const redis = new Redis({
port: 6379,
host: 'your-redis-host',
connectTimeout: 10000 // optional
});
You can try connecting using ioredis.
var Redis = require('ioredis');
var config = require("./config.json");
const redis = new Redis({
host: config.host,
port: config.port,
password: config.password, // If you have any.
tls: {}, // Add this empty tls field.
});
redis.on('connect', () => {
console.log('Redis client is initiating a connection to the server.');
});
redis.on('ready', () => {
console.log('Redis client successfully initiated connection to the server.');
});
redis.on('reconnecting', () => {
console.log('Redis client is trying to reconnect to the server...');
});
redis.on('error', (err) => console.log('Redis Client Error', err));
//check the functioning
redis.set("framework", "AngularJS", function(err, reply) {
console.log("redis.set ", reply);
});
redis.get("framework", function(err, reply) {
console.log("redis.get ", reply);
});

Socket IO namespace not working with Express

I have tried setting up a namespace on the backend,
const server = require("http").createServer(app);
const connectedUsers = {};
const io = require("socket.io")(server, {
path: "/socket",
serveClient: false,
// below are engine.IO options
pingInterval: 10000,
pingTimeout: 5000,
cookie: false
});
const singularConnection = io.of("/singular-socket");
singularConnection.on("connection", socket => {
console.log("unique user connected with socket ID " + socket);
}
And on my client, I try connecting with,
const socket = io(GATEWAY, {
path: "/socket/singular-socket",
transports: ["websocket"],
jsonp: false
});
socket.connect();
socket.on("connect", () => {
console.log("connected to socket server");
});
I've tried different variation of the URL, getting rid of /socket and moving other stuff around, but I can't seem to get it working. What am I doing wrong here?
I don't have any experience in using socket.io, but from the docs...
To connect to a namespace, the client code would look like.
const socket = io('http://localhost/admin', {
path: '/mypath'
});
Here, the socket connects to the admin namespace, with the custom path
mypath.
The request URLs will look like:
localhost/mypath/?EIO=3&transport=polling&sid= (the namespace is
sent as part of the payload).
Following the above lines, your code should look like..
const socket = io("http://localhost/singular-socket", {
path: "/socket",
transports: ["websocket"],
jsonp: false
})
Where /singular-socket is the namespace and /socket is the path.
Try this repl

Api request from nodejs

It is necessary to obtain data from https://forkdelta.io using api https://github.com/forkdelta/backend-replacement/tree/master/docs/api
Here is the code:
var http = require("http");
http.createServer(function(request, response) {
const io = require('socket.io-client');
socket = io.connect('https://api.forkdelta.com', { transports:
['websocket'] });
socket.on('connect', function() {
console.log('socket connected');
socket.emit('getMarket', {
token: "0x6fff3806bbac52a20e0d79bc538d527f6a22c96b",
user: "" });
});
socket.on('market', function(payload) {
console.log(payload.orders.buys);
});
}).listen(3000);
console.log("Server has started.");
I save it in server.js and execute the command node server.js
I run the code at the link http: // localhost: 3000 from the local server - hangs
I run the code from here https://repl.it/repls/DeafeningBlushingAddons - successfully
Please help me figure out how to correctly run the code from the browser. Next, we intend to parse the data array and convert it to a table.
Please check the console from where you are executing this code, it is actually fetching the data you require...
This is what the data looks like
{ id: '0xd7ff1f49ffde2380b1fd42877b8ce573bfb2c1cace509b1edcb07e757fa13889_buy',
user: '0x5b38d2298666c89efe5f1819347a6004b93bbbe2',
state: 'OPEN',
tokenGet: '0x6fff3806bbac52a20e0d79bc538d527f6a22c96b',
amountGet: '3.50e+22',
tokenGive: '0x0000000000000000000000000000000000000000',
amountGive: '3.500e+15',
expires: '104747875',
nonce: '1340442292',
v: 27,
r: '0xc929ec3f336b4641d84545d27764c43470946c3119221c856c8f72ac3f625edb',
s: '0x5a79fe5728fb47d22c837ae322bff8b43f3de638ddfa3ee5122bf344a0e507dc',
date: '2018-02-14T20:18:30.052233',
updated: '2018-10-02T10:06:53',
availableVolume: '3.15e+18',
ethAvailableVolume: '3.150000000',
availableVolumeBase: '3.150e+11',
ethAvailableVolumeBase: '3.150000000e-7',
amount: '-3.15e+18',
amountFilled: '0',
price: '1e-7' }

ember-cli-mirage redirects socket.io client, which is injected in mirage

the issue that occurs here, is that, when i connect between sample socekt.io client with this socket.io server by node.js ( just running two terminals and opening socket connection between client and server)
I have no problems. But, when I am trying to inject this socket.io-client into my Ember.js application, precisely to ember-cli-mirage it redirects my client from given address : ( 'http: //localhost:8080') to something like http: //localhost:8080/socket.io/?EIO=3&transport=polling&.....
also Mirage displays me an error that I cannot handle, even by setting up precise namespace, routing the wsClient.connect() method or calling this.passthrough() , before calling wsClient.connect() .
I also paste the the screenshot of error from inspect console in browser:
error image
Do you have any idea how to resolve this problem? Thank you in advance and I also hope that the topic is not duplicated.
// server.js
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
app.listen(8080);
function handler(req, res) {
res.writeHead(200);
res.end('default.index');
}
var rooms = {
'room1': [
],
'room2': [
]
};
io.on('connection', function(socket) {
console.log('client connected');
socket.on('join', function(roomName) {
rooms[roomName].push(socket.id);
socket.join(roomName);
});
socket.on('leave', function(roomName) {
var toRemove = rooms[roomName].indexOf(socket.id);
rooms[roomName].splice(toRemove, 1);
socket.leave('roomName');
});
socket.on('eNotification', function(data) {
console.log(data);
io.to(socket.id).emit('eNotificationCall', data);
io.to('room2').emit('eventNotification', data);
});
socket.on('gNotification', function(data) {
console.log(data);
io.to(socket.id).emit('gNotificationCall', data);
io.to('room1').emit('diagram1Notification', data);
});
socket.on('close', function() {
console.log('client disconnected');
});
});
//client.js
var wsClient = {
socket: null,
connect: function() {
this.socket = io.connect('http://localhost:8080');
this.socket.on('connect', function() {
console.log('mirage client connected!');
});
},
send: function(eventData, graphData) {
this.socket.emit('eNotification', eventData);
this.socket.emit('gNotification', graphData);
}
};
export default wsClient;
//config.js
import wsClient from './websockets/client';
export default function() {
wsClient.connect();
console.log(wsClient.socket);
var graphData = {X: "2", Y: "3"};
var eventData = {myDAta: 'myDAta', message: 'message'};
setInterval(function() {
wsClient.send(graphData, eventData);
}, 5000);
}
If you call this.passthrough() with no args it only allows requests on the current domain to passthrough. It looks like the websocket connection is on a different port, so try specifying it directly:
this.passthrough('http://localhost:8080/**');
See the docs for more information.

Categories