Setting up socket.io server on AWS EC2 - node.js

I've got a problem to run the server with socketIO module on AWS EC2 server.
error1 screenshot
I have tried to edit inbound rule but it did not work
error2 screenshot
Code works perfect on localhost but when I try it on aws ec2 , it is not working.
Frontend port : 80
backend socket.io server : 8081
tcp socket server: 8124
FRONTEND CODE
import React, {Component} from "react";
import socketIOClient from "socket.io-client";
class Nokta extends Component {
constructor() {
super();
this.state = {
res_enlem: 41.018350,
endpoint: "http://172.31.36.93:8081",
};
}
componentDidMount() {
const {endpoint} = this.state;
//Very simply connect to the socket
const socket = socketIOClient(endpoint);
socket.on("giden enlem", data => {
this.setState({res_enlem: data.enlem});
});
}
render() {
return (
<Marker
latitude={this.state.res_enlem}
longitude={this.state.res_boylam}>
</Marker>
)
}
}
export default Nokta;
website = website link

Related

How to resolve socket.io Error "TransportError: xhr poll error"

I want to make a socket.io server using NestJS.
I'm trying communication between server and client on localhost.
however, client(socket.io-client) throw the following error.
TransportError: xhr poll error
the server was running on localhost:3000. and the client was run from node command(node index.js)
server (mock.gateway.ts)
import { SubscribeMessage, WebSocketGateway, MessageBody, ConnectedSocket, WebSocketServer} from '#nestjs/websockets';
import { Socket } from 'socket.io';
#WebSocketGateway()
export class MockGateway {
#WebSocketServer()
server;
#SubscribeMessage('mock')
mock(
#MessageBody() data: string,
#ConnectedSocket() socket: Socket
): void {
console.log(data);
}
}
server (main.ts)
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
client
import { io, Socket } from 'socket.io-client';
const socket = io('ws://localhost:3000', {
path: '/socket.io',
});
socket.emit('mock', 'mock');
I tried set transports to the sockect.io-client. but it makes a timeout error.
import { io, Socket } from 'socket.io-client';
const socket = io('ws://localhost:3000', {
path: '/socket.io',
transports: ['websocket'],
});
socket.emit('mock', 'mock');
Maybe a mistake in module settings. so I use the wscat is debug-tool. It throws the following error, I'm wondering why wscat can connest Nest server.
$ wscat -c ws://localhost:3000/socket.io/\?transport=websocket
Connected (press CTRL+C to quit)
error: Invalid WebSocket frame: RSV1 must be clear
If anyone has any ideas, please comment.

NestJS and IPFS - no connection on the server instance

I am struggling with binding IPFS node with NestJS instance on the server. All was working fine on the local machine, but on the server, I have a working instance of the IPFS. I know that it works as I can see connected peers and I can see a file uploaded through the server console by https://ipfs.io/ipfs gateway.
The code of the IPFS service is quite simple and it does not produce any errors until I try to upload something.
import { Injectable } from '#nestjs/common';
import { create } from 'ipfs-http-client';
#Injectable()
export class IPFSClientService {
private client = create({
protocol: 'http',
port: 5001
});
public async upload(file: Express.Multer.File): Promise<string> {
const fileToAdd = { path: file.filename, content: file.buffer };
try {
const addedFile = await this.client.add(fileToAdd, { pin: true });
return addedFile.path;
} catch (err) {
console.log('err', err);
}
}
}
Unfortunatelly the error message is enigmatic.
AbortController is not defined
at Client.fetch (/home/xxx_secret/node_modules/ipfs-utils/src/http.js:124:29)
at Client.fetch (/home/xxx_secret/node_modules/ipfs-http-client/cjs/src/lib/core.js:141:20)
at Client.post (/home/xxx_secret/node_modules/ipfs-utils/src/http.js:171:17)
at addAll (/home/xxx_secret/node_modules/ipfs-http-client/cjs/src/add-all.js:22:27)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at Object.last [as default] (/home/xxx_secret/node_modules/it-last/index.js:13:20)
at Object.add (/home/xxx_secret/node_modules/ipfs-http-client/cjs/src/add.js:18:14)
at IPFSClientService.upload (/home/xxx_secret/src/ipfs/ipfs-client.service.ts:20:25)
I will appreciate any help in this matter as I don't have ideas regarding this issue :/

How to open port with Fastify?

I'm trying to use Fastify with my project, but when I want to start the server, it isn't opening the specific port.
I'm creating the server like this:
import { NestFactory } from "#nestjs/core";
import { NestFastifyApplication, FastifyAdapter } from "#nestjs/platform-fastify";
import { AppModule } from "./app.module";
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter()
);
await app.listen(3000, '0.0.0.0');
}
bootstrap();
It says the application is successfully started, but when I check with netstat -ano,
the address(0.0.0.0:3000) isn't there.
The server logs:

Socket connection from NextJS to a node backend

I am trying to implement a basic socket connection from my NextJS client side (running on localhost:3000) to my NestJs server (running on localhost:3003).
The server code looks like this
ChatGateway.ts
import {
SubscribeMessage,
WebSocketGateway,
OnGatewayInit,
WebSocketServer,
OnGatewayConnection,
OnGatewayDisconnect,
} from '#nestjs/websockets';
import {
Logger
} from '#nestjs/common';
import {
Socket,
Server
} from 'socket.io';
#WebSocketGateway()
export class ChatGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
#WebSocketServer() server: Server;
private logger: Logger = new Logger('ChatGateway');
#SubscribeMessage('msgToServer')
handleMessage(client: Socket, payload: string): void {
console.log(payload);
this.server.emit('msgToClient', payload);
}
afterInit(server: Server) {
this.logger.log('Init');
}
handleDisconnect(client: Socket) {
this.logger.log(`Client disconnected: ${client.id}`);
}
handleConnection(client: Socket, ...args: any[]) {
this.logger.log(`Client connected: ${client.id}`);
this.server.emit('msgToClient', "payload");
}
}
ChatModule.ts
import { Module } from '#nestjs/common';
import { TypeOrmModule } from '#nestjs/typeorm';
import { ChatGateway } from "./chat.gateway";
#Module({
imports: [],
controllers: [],
providers: [ChatGateway],
})
export class ChatModule {}
AppModule.ts
#Module({
imports: [TypeOrmModule.forRoot(), NewsletterModule, AuthModule, UsersModule, ListingsModule, ChatModule]
})
export class AppModule {
constructor(private connection: Connection) {}
But when I try to connect to the socket from my client side
import {
io
} from "socket.io-client";
function Chat() {
const socket = io("http://127.0.0.1:3003");
useEffect(() => {
console.log("chat useEffect")
socket.emit('msgToServer', "message")
}, [])
socket.on('msgToClient', (message) => {
console.log(message)
})
I am not getting any errors, but also there is nothing happening when I emit or try to receive events from the server.
Even the server console doesnt log the emit events. The only thing that happens on the server is that the client gets connected and disconnected all the time without even me doing anything
Any idea why cant I connect to the sockets and why is the server constantly connecting and disconnecting even if I disable the socket connection form the client side.
Thanks!
Socket.io client needs to be version 2. Version 3 and 4 are breaking changes and don't communicate with a v2 server. Once Nest v8 hits, socket.io v4 will be used by default.

REST client proxy issue in VScode

When using the REST client extension in VSCode eg.
Send Request
GET http://localhost:4200/dashboard
###
I get following error :
Connection is being rejected. The service isn’t running on the server,
or incorrect proxy settings in vscode, or a firewall is blocking requests.
Details: RequestError: connect ECONNREFUSED 127.0.0.1:4200
How can I change my http-proxy to 4200 instead of 127.0.0.1:4200 ?
The solution that works for me, it's to change the server hostname with a string (hostname: "127.0.0.1").
Deno/TS/Rest client Extension vscode
app.ts
import { Drash } from "https://deno.land/x/drash#v1.4.3/mod.ts";
import { Api } from "./api.ts";
const server = new Drash.Http.Server({
response_output: "application/json",
resources: [Api],
});
server.run({
hostname: "127.0.0.1", // Just here !
port: 1854,
});
console.log("Server running...");
api.ts
// #ts-ignore
import { Drash } from "https://deno.land/x/drash#v1.4.3/mod.ts";
export class Api extends Drash.Http.Resource {
static paths = ["/"];
public GET() {
this.response.body = `Hello World! (on ${new Date()})`;
return this.response;
}
}
req.http
GET http://localhost:1854/ HTTP/1.1
OR
GET http://127.0.0.1:1854/ HTTP/1.1

Resources