Whoops! Lost connection to http://198.x.x.x:hostnumber/websocket - websocket

I am using SocksJs and getting every time Whoops! Lost connection to Http or if I changed the link to ws://198.x.x.x:hostnumber/websocket then i will get
'SyntaxError: The URL's scheme must be either 'http:' or 'https:'. 'ws:' is not allowed.
SyntaxError: The URL's scheme must be either 'http:' or 'https:'. 'ws:' is not allowed.'
also, I am sharing my code
import * as Stomp from 'stompjs';
import * as SockJS from 'sockjs-client';
connectNew() {
const socket = new SockJS(this.serverUrl);
this.stompClient = Stomp.over(socket);
this.stompClient.connect('', '', () => {
console.log('success');
});
}
Please help if anybody knows the answer I want to run this code on my mobile phone

Related

Why is my Socket.IO server not responding to my Firecamp and C# clients?

I am trying to set up a very basic Socket.IO server and a .NET / Firecamp client to learn how to send events between the two.
My Javascript Socket.IO server is set up like this:
const
http = require("http"),
express = require("express"),
socketio = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = socketio(server);
const SERVER_PORT = 3000;
io.on("connection", () => {
console.log("Connected");
io.emit("foo", "123abc");
});
server.listen(SERVER_PORT);
I am able to connect with a simple Socket.IO Javascript file:
const
io = require("socket.io-client"),
ioClient = io.connect("http://localhost:3000");
ioClient.on('connect', () => {
console.log("connected");
});
When I try to connect with Firecamp or this C# library I never see a connection event fired.
I looked at the default options for the Socket.IO JS client and tried to reproduce them in Firecamp: https://socket.io/docs/v3/client-api/index.html
The most important ones seem to be the Path= /socket.io, ForceNew = True, and Transports = polling, websocket. I decided to remove the polling transport because I kept getting an XHR polling error, but the websocket also times out in both C# and Firecamp.
I have tried connecting to "http://localhost:3000" and just "http://localhost".
Here is a screenshot of my Firecamp settings
I am also seeing a similar issue with my C# program
Quobject.Collections.Immutable.ImmutableList<string> trans = Quobject.Collections.Immutable.ImmutableList.Create<string>("websocket");
IO.Options options = new IO.Options();
options.Port = 3000;
options.Agent = false;
options.Upgrade = false;
options.Transports = trans;
client = IO.Socket("http://localhost:3000", options);
client.On(Socket.EVENT_CONNECT, () =>
Console.WriteLine("Connected"));
client.On(Socket.EVENT_CONNECT_ERROR, (Data) => Console.WriteLine("Connect Error: " + Data));
client.On(Socket.EVENT_CONNECT_TIMEOUT, (Data) => Console.WriteLine("Connect TImeout Error: " + Data));
client.On(Socket.EVENT_ERROR, (Data) => Console.WriteLine("Error: " + Data));
client.Connect();
If I only use a websocket transport I timeout in both Firecamp and C#. If I enable polling I receive the below error:
Error: Quobject.EngineIoClientDotNet.Client.EngineIOException: xhr poll error ---> System.AggregateException: One or more errors occurred. ---> System.Net.WebException: The remote server returned an error: (400) Bad Request.
at System.Net.HttpWebRequest.GetResponse()
at Quobject.EngineIoClientDotNet.Client.Transports.PollingXHR.XHRRequest.<Create>b__7_0()
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at Quobject.EngineIoClientDotNet.Client.Transports.PollingXHR.XHRRequest.Create()
--- End of inner exception stack trace ---
What other configuration settings can I toggle to try to get my Firecamp or C# connection to show up in my JS Server? I am receiving an "XHR Poll error" from the polling transport, and a timeout from the websocket transport. Is there additional debugging info somewhere I can use to determine where my problem lies? I think if I can get the communication working in either Firecamp or C# I should be able to get it working in the other environment.
I am assuming you're using the SocketIO v3 client. Firecamp is only supporting SocketIO v2. But the good news is in just two days Firecamp is going to give support for SocketIO v3 in the new canary release. I'll keep you posted here.
edited on 7th Sep'21
Firecamp is now supporting SocketIO v2, v3, and v4.
As mentioned above, Firecamp isn't optimized yet for the new version of Socket.IO (v4).
so meanwhile you can choose to manually enable compatibility for Socket.IO v2 clients.
All you have to do is to add "allowEIO3: true" (without quotes) as a key:value pair to the option object and pass this object when you create the server.
this will allow you to communicate with the server via Firecamp.
source https://socket.io/docs/v4/server-api/#Server
below you'll find an example for a working socket.io server integrated with express server.
const app = require('express')();
const httpServer = require('http').createServer(app);
const options = {
allowEIO3: true,
};
const io = require('socket.io')(httpServer, options);
app.get('/', (req, res) => {
res.send('home endpoint');
});
io.on('connection', (socket) => {
socket.on('new-connection', (data) => {
console.log(socket.id, 'connected');
socket.broadcast.emit('test-event', { name: data.name });
});
// when the user disconnects.. perform this
socket.on('disconnect', () => {
console.log(`${socket.id} disconnected`);
});
});
const port = 3000;
httpServer.listen(port, () => {
console.log(`server running on port ${port}`);
});

Is there analog of express's app.set( 'something', something ) in koa?

I need socket.io instance in several places in my app. To achieve this in express i can do this:
app.set('io', io);
In koa right now i have this:
app.use( async ( ctx, next ) => {
ctx.io = io;
await next();
});
This works, but this middleware executes every time my server recieves request. Is there a better way to do this?
I don't know how you are fully implementing but there are a couple things that you can do is you can either pass an addition argument and upgrade the connection to a websocket that will bypass the rest of the middlewares. Or, what I do personally is just have any websocket connection go to a different end point. This will help with any future scalability issues. for example, if you need to create clusters of your server then you will have more control as well will help you testing your backend easier. That's what I would do atleast. My socket.io back end looks like this:
server.ts
oh yea I'm using typescript in the back end
require('dotenv').config({ path: __dirname + '/.env' });
import Koa from 'koa';
const koa = new Koa();
import cors from '#koa/cors';
const PORT = process.env.CHAT_PORT || 3000;
const ENV = process.env.NODE_ENV || 'development';
const server = require('http').createServer(app, { origins: 'http://server.ip' });
const io = (module.exports.io = require('socket.io')(server));
import SocketManager from './lib/SocketManager';
app.use(
cors({
origin: '*',
optionsSuccessStatus: 200,
}),
);
// server setup
server.listen(PORT, (err: ErrorEvent): void => {
if (err) console.error('❌ Unable to connect the server: ', err);
console.log(`💻 Chat server listening on port ${PORT} - ${ENV} environment`);
});
io.on('connection', SocketManager);
then just create a socket manager that imports the io instance and you can then go ahead and handle all the connections.
I hope this is the answer you were looking for/gave you some better insight.

Can't connect to web socket from Electron when using self signed cert

I have an Electron app which tries to connect to a device over a web socket. The connection is encrypted (i.e. wss) but the SSL certificate is self signed and thus, untrusted.
Connecting inside Chrome is ok and it works. However inside Electron I run into problems. Without putting any certificate-error handlers on the BrowserWindow or on the app I receive the following error in the console output:
WebSocket connection to 'wss://some_ip:50443/' failed: Error in connection establishment: net::ERR_CERT_AUTHORITY_INVALID
Then shortly after:
User is closing WAMP connection.... unreachable
In my code, to make the connection I run the following.
const connection = new autobahn.Connection({
realm: 'some_realm',
url: 'wss://some_ip:50443'
});
connection.onopen = (session, details) => {
console.log('* User is opening WAMP connection....', session, details);
};
connection.onclose = (reason, details) => {
console.log('* User is closing WAMP connection....', reason, details);
return true;
};
connection.open();
// alternatively, this also displays the same error
const socket = new WebSocket(`wss://some_ip:50443`);
socket.onopen = function (event) {
console.log(event);
};
socket.onclose = function (event) {
console.log(event);
};
NOTE: Autobahn is a Websocket library for connecting using the WAMP protocol to a socket server of some sort. (in my case, the device) The underlying protocol is wss. Underneath the code above, a native JS new WebSocket() is being called. In other words:
As I mentioned, I've tested this code in the browser window and it works. I've also built a smaller application to try and isolate the issue. Still no luck.
I have tried adding the following code to my main.js process script:
app.commandLine.appendSwitch('ignore-certificate-errors');
and
win.webContents.on('certificate-error', (event, url, error, certificate, callback) => {
// On certificate error we disable default behaviour (stop loading the page)
// and we then say "it is all fine - true" to the callback
event.preventDefault();
callback(true);
});
and
app.on('certificate-error', (event, webContents, link, error, certificate, callback) => {
// On certificate error we disable default behaviour (stop loading the page)
// and we then say "it is all fine - true" to the callback
event.preventDefault();
callback(true);
});
This changed the error to:
WebSocket connection to 'wss://some_ip:50443/' failed: WebSocket opening handshake was canceled
My understanding is that the 'certificate-error' handlers above should escape any SSL certificate errors and allow the application to proceed. However, they're not.
I've also tried adding the following to main.js:
win = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
webSecurity: false
}
});
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = '1';
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
With Election, how do I properly deal with a certificate from an untrusted authority? i.e. a self signed cert.
Any help would be much appreciated.
I had the same problem , all i added was your line:
app.commandLine.appendSwitch('ignore-certificate-errors');
I use socket.io, but i think its the same principal.
I do however connect to the https protocol and not wss directly.
This is what my connection looks like on the page:
socket = io.connect(
'https://yoursocketserver:yourport', {
'socketpath',
secure: false,
transports: ['websocket']
});
That seems to have done the trick.
Thank you for the help :) i hope this answer helps you too.

socket.io-client keeping on connecting when using in react-native

I want to use the websocket in my RN project. And I did it using the ws at server side and the RN built-in websocket implementation.
But it seems not so convinient since I use socket.io before.
So I tried to use socket.io:
In RN:
import './userAgent'
import io from "socket.io-client/socket.io"
In component:
componentDidMount() {
this.socket = io('https://localhost:4080',{jsonp: false});
this.socket.on('hello', (msg) =>{
this.setState({response:msg})
});
}
In the server:
io.on('connection', function(socket){
socket.emit('hello','hello world')
console.log('a user connected');
socket.on('disconnect',function(){
console.log('user disconnected')
})
})
And in userAgent.js
window.navigator.userAgent = 'react-native';
That is just the result I googled and they said it will work. But for me, the chrome debugger stopped at:
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
return r;
}
And it says the storage is not defined.
Then I looked into the socket.io.js and find that the exports.storage is window.localStorage. So I disabled the remote js debug, and the code began running.
But the server continues to log : a user connected . as if my RN app is keeping on connecting to the server. And it seems the socket.on() did not work at client side.
react-native version:0.27.2
socket.io-client version:1.4.8
Anyone knows where is going wrong?
Well,finally I found the solution after looking through the socket.io source.
It seems that the socket.io does not use 'websocket' as transport defaultly. It will use the 'polling' in my case, so just explicityly set it :
componentDidMount() {
var socket = io('http://localhost:4080', { jsonp: false, transports: ['websocket'] })
socket.on('hello', (msg) => {
//do something
});
}
Now it works.
But what still confuses me is that in brower client I do not set the transports and it just work well but in react-native it doesn't. Not figured out why.

Autobahn 0.9.5 (AMD) - Error during WebSocket handshake

I'm trying to implement autobahn 0.9.5 on my SPA project using DurandalJS.
var ab = require('autobahn');
live = new ab.Connection(
{
url: 'ws://localhost:8080',
realm: 'realm1'
});
live.onopen = function(session, details)
{
console.log('Autobahn open successfully!', session);
};
live.onclose = function(reason, details)
{
console.log('Autobahn connection lost', reason + ' - ' + details);
};
live.open();
i received an error on firefox and chrome browser
Firefox:
InvalidAccessError: A parameter or an operation is not supported by the underlying object
websocket.close(code, reason);
Chrome:
WebSocket connection to 'ws://localhost:8080/' failed: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received
I have no idea what happened..
BEFORE I STARTED WITH - autobahn 0.9.5
I have write simple test on test.html to see if everything setup in backend is correct.
But on this test i currently used autobahn 0.8.2
test.html
<script src="http://autobahn.s3.amazonaws.com/js/autobahn.min.js"></script>
<script>
var conn = new ab.Session(
// Websocket host
'ws://localhost:8080',
// Callback on connection established
function() {
// Once connect, subscribe to channel
conn.subscribe('3', function(topic, data) {
console.log(topic, data);
});
},
// Callback on connection close
function() {
console.warn('WebSocket connection closed');
},
// Additional AB parameters
{'skipSubprotocolCheck': true}
);
</script>
This test working perfectly as what i need, but after I try to implement it inside real project, I can't make autobahn 0.8.2 loaded using requireJS, It keep give me an error ab not defined.
I don't really understand what is happening, according of autobahn getting started, it should work.
and here is how I define it on main.js (requirejs paths and shim config)
requirejs.config({
paths: {
'autobahn' : 'https://autobahn.s3.amazonaws.com/autobahnjs/latest/autobahn.min',
'when' : 'https://cdnjs.cloudflare.com/ajax/libs/when/2.7.1/when'
},
shim: {
'autobahn': {
deps: ['when']
}
}
});
Hopefully somebody can help me, I really love to make it working !
Any help will be greatly appreciated!
Thanks
Probably late, but for further reference.
This is probably not a complete answer to SO question.
First of all, everything should be written either for AutobahnJS v0.8.2 (which supports WAMPv1) or for AutobahnJS v0.9.5 (WAMPv2).
Check API documentation.
WAMP v1
AutobahnJS v0.8.2 API - http://autobahn.ws/js/reference_wampv1.html
it loads from http://autobahn.s3.amazonaws.com/js/autobahn.js
global variable for autobahn is ab
connecting with var conn = new ab.Session(wuri, onOpenCallback, onCloseCallback, options);
WAMP v2
AutobahnJS v0.9.5 API - http://autobahn.ws/js/reference.html
it loads from https://autobahn.s3.amazonaws.com/autobahnjs/latest/autobahn.min.jgz
global variable for autobahn is autobahn
connecting with new autobahn.Connection({url: wuri, realm: yourRealm});

Resources