Nats client connection error with web sockets - nats.io

I am getting problem while connecting the nats.io with web socket ? "failed to reload", how we can connect with web sockets?
I think that have SSL issue but not sure about that , I have already tried many times with web sockets and socket.io but didn't get success.
import React from "react";
function App() {
React.useEffect(() => {
var dummy = new WebSocket("ws://localhost:4222/");
dummy.onclose = function (e) {
console.log("Closed Running")
console.log(e)
}
dummy.onopen = function(e) { console.log("Opened Running")}
dummy.onmessage = function(e) { console.log(e); };
// dummy.send("Here's some text that the server is urgently awaiting!");
});
return (
<div className="App">
<h1>Testing</h1>
</div>
);
}
export default App;

The transport runs over websockets, but you still need to use the nats.ws client in order to connect as it implements the nats clients protocol.
See https://github.com/nats-io/nats.ws.

Related

Oak framework Doesnt respond to request in deno deploy

I tried deploying my deno app to deno deploy but I have tried all means to work but still no response and I have no error in logs.
This my code below..
import { load } from "https://deno.land/std#0.171.0/dotenv/mod.ts";
import { Application } from "https://deno.land/x/oak#v11.1.0/mod.ts";
import { socketIo } from "../src/controllers/websocket/setup.ts";
import fileRouter from "./../src/routes/file_rt.ts";
import ordersRouter from "./../src/routes/orders_rt.ts";
import mealRouter from "./../src/routes/meal_rt.ts";
import userRouter from "./../src/routes/user_rt.ts";
load();
const app = new Application();
app.use(await rateLimit);
app.use(userRouter.routes());
app.use(ordersRouter.routes());
app.use(mealRouter.routes());
app.use(fileRouter.routes());
app.use(userRouter.allowedMethods());
app.use(ordersRouter.allowedMethods());
app.use(mealRouter.allowedMethods());
app.use(fileRouter.allowedMethods());
socketIo();
await app.listen({port:80});
I tried to test an api route using postman but the endpoint didn't log anything
I have fixed it by removing the socket IO connection I imported. [ socketIO() ]
But now the socket connection is not working.
export const socketIo = async () => {
io.on("connection", (socket) => {
console.log(`socket ${socket.id} connected`);
skt = socket;
signUSER(socket);
socket.on("disconnect", (reason) => {
console.log(`socket ${socket.id} disconnected due to ${reason}`);
});
console.log("Socket Hit 😎✨");
});
await serve(io.handler(), {
port: 3000,
});
}

Fail to connect to socket.io server on Window Server in dotnet core

I host a very simple node socket IO application on my Window Server, below are the code sample.
// socket.io 3.1.2"
const port = 30080;
const httpServer = require("http").createServer();
const io = require("socket.io")(httpServer, {
cors: {
origin: '*',
methods: ["GET", "POST"],
allowedHeaders: ["Access-Control-Allow-Origin"],
credentials: false
}
});
io.on("connection", socket => {
console.log('On Connection');
io.emit("message", 'Welcome to Socket Io.');
});
And I wrote some code to try connect to my socket IO server in a HTML File and work well. below are the code sample.
// <script src="https://cdn.socket.io/3.1.3/socket.io.min.js"></script>
const socket = io("http://myserverip:30080", {
withCredentials: false,
extraHeaders: {
"Access-Control-Allow-Origin": "*"
}
});
socket.on("connect", () => {
console.log('connect');
});
socket.on("message", (message) => {
console.log(message);
});
But when I try to use those above code in my .NET Core web application, I get the error "ERR_SSL_PROTOCOL_ERROR". Even I publish my web application on the Window Server still getting the same error message.
I have tried http, https, ws and wss protocol. None of these work. How can I get this possibly working?
I do not see the following in your server side code:
httpServer.listen()
Do you have a reverse proxy between your client and the server?
I would expect no SSL related error based on you code.
I would also use socket.io version 4 just for future maintenance reasons.

Get the client IP on NextJS and use SSR

I'm making a weather app, and I get the client IP with IPIFY, but this loses SSR, or I use SSR and I get the server IP. Someone told
me that I could use the header x-forwarded-for and then, with this value, make the weather API call with SSR.
The problem is I'm using only nextjs, no backend here, and second, I don't know how to call or use x-forwarded-for in the front to get the client IP.
Is this possible?
How I can implement that?
I'm using vercel to deploy the app.
Updated answer as request.connection is deprecated since Node.js v13.0.0. So we should now use request.socket instead.
export const getServerSideProps = async ({ req }) => {
const forwarded = req.headers['x-forwarded-for'];
const ip = typeof forwarded === 'string' ? forwarded.split(/, /)[0] : req.socket.remoteAddress;
console.log(ip);
return {
props: { ip },
};
};
Here you go:
export async function getServerSideProps({ req }) {
const forwarded = req.headers["x-forwarded-for"]
const ip = forwarded ? forwarded.split(/, /)[0] : req.connection.remoteAddress
return {
props: {
ip,
},
}
}
I think you can get them through getServerSideProps.
export async function getServerSideProps({ req }) {
console.log(req.headers) //see if you have those headers
return {
props: {
headers
},
}
}
function Page({ headers }) {
// Render data...
}

SignalR message from client not received

I was initially trying to setup my server-side signalR HUB to send messages to the client, but so far have not succeeded.
So I decided to try to send a message from the client instead; and setup a button to trigger a message from client to server.
I can launch my Core 3.1 project (image below), and setup the Hub connection just fine, but cannot verify in any way that the message is being received on the server.
In fact, my server breakpoints never get hit.
In my html:
<button mat-button (click)="sendClientMessage()"> Send Message </button>
TypeScript component:
sendClientMessage(): void {
this.notificationService.sendMessageToHub();
}
import { Injectable } from '#angular/core';
import * as signalr from '#microsoft/signalr';
import { SIGCONT } from 'constants';
#Injectable({
providedIn: 'root',
})
export class NotificationService {
private hubConnection: signalr.HubConnection;
hubMessage: string;
public startConnection = () => {
this.hubConnection = new signalr.HubConnectionBuilder()
.withUrl('https://localhost:44311/hub')
.configureLogging(signalr.LogLevel.Debug)
.build();
this.hubConnection
.start()
.then(() => {
console.log('Hub Connection started');
this.sendMessageToHub();
})
.catch((err) => console.log(`Error while starting connection: ${err}`));
this.hubConnection.serverTimeoutInMilliseconds = 50000;
}
public hubListener = () => {
this.hubConnection.on('messageReceived', (message) => {
this.hubMessage = message;
console.log(message);
});
}
public sendMessageToHub = () => {
if (this.hubConnection == undefined || this.hubConnection.state === signalr.HubConnectionState.Disconnected) {
this.startConnection();
} else {
this.hubConnection.send('NewMessage', 'client', 'You have a notification from the front end !')
.then(() => console.log('Message sent from client.'));
}
}
constructor() { }
}
My server-side Core project - Notifications.cs
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NotificationHub.Hubs
{
public class Notifications: Hub
{
public async Task NewMessage(long username, string message)
{
await Clients.All.SendAsync("messageReceived", username, message);
}
internal Task NewMessage(string v1, string v2)
{
throw new NotImplementedException();
}
}
}
When I click the button above, it appears to send something to the server:
I would appreciate any help in getting my Core project to first hit those breakpoints, and to see what the NewMessage method is not receiving the client message.
From there I can try and figure out how to send messages from server to client (i.e. using some Timer example).
thank you.
You're sending 2 strings from the client to the server but you've made your server method take a long and a string so it doesn't match. If you looked at the server logs you would see a message about the method no being found.
Another way to observe the error would be to call invoke instead of send from the client side which will expect a response from the server on completion of the hub method, or in this case an error will be sent from the server.

How to connect meteor server to another tcp server via tcp socket

I want to create a meteor application that connect meteor server to another tcp server,
that is meteor server is client side and another tcp server is server side.
1.It like WebSocket of browser ,but I want use it on meteor server ,not on meteor client .
WebSocket using like :
var tcpServer = "ws://some.tcpServer.org/";
socket = new WebSocket(tcpServer,options);
socket.onopen = function(evt) { onOpen(evt) };
socket.onclose = function(evt) { onClose(evt) };
socket.onmessage = function(evt) { onMessage(evt) };
socket.onerror = function(evt) { onError(evt) };
2.Maybe as follow :
if (Meteor.isServer) {
Meteor.startup(function () {
var tcpServer = "ws://some.tcpServer.org/";
socket = new socketClient(tcpServer,options);
socket.onopen = function(evt) { onOpen(evt) };
socket.onclose = function(evt) { onClose(evt) };
socket.onmessage = function(evt) { onMessage(evt) };
socket.onerror = function(evt) { onError(evt) };
})
}
3.Or ...
var net = Npm.require('net');
net.createServer(function(socket){...} is for server side , not fit for my idea.
Maybe like net.createClient(function(tcpServer, options ){...} , but no this method.
I had been looking around but i do not see a method for Meteor. Can anyone give any pointers for me to start?
Thank a lot !
There are several problems with what you described.
WebSocket, which works over HTTP, and TCP are completely different protocols. You will not be able to open a WebSocket connection to a TCP server.
To have the Meteor server communicate with another server over TCP, you'll want to use Node's net API. To use this with Meteor, you'll need to use async callbacks in a way that is compatible with Fibers; see this blog post for an overview and https://stackoverflow.com/a/21542356/586086.
Here you have link to working plugin:
websocketify on atmosphere.com

Resources