Svelte/Sveltekit and socket.io-client not working in dev (works in preview) - socket.io

I'm trying to make socket.io-client work in a svelte front end app to talk to an existing API server that already uses socket.io. After a number of challenges, I managed to make this work but I can only get this to work with sveltekit's preview and not in dev mode. Wondered if someone with some knowledge of those could explain why or suggest what I need to do to get it connecting in dev?
svelte 3.34.0
sveltekit next-169
socket.io(-client) 4.2.0
basic code as follows, currently within a file $lib/db.js where I define a few stores that are pulled into the layout for general use..
import { io } from "socket.io-client";
import { browser } from '$app/env';
const initSocket = async () => {
console.log('creating socket...');
let socket = io('http://192.168.1.5:4000', { 'connect timeout': 5000 });
socket.on("connect", () => {
// always works in preview...
console.log('socket created with ID:', socket.id);
});
socket.on("connect_error", (error) => {
// permanently fired in dev...
console.error('Failed to connect', error);
});
socket.on("error", (error) => {
console.error('Error on socket', error);
});
socket.on("foo", data => {
// works in preview when server emits a message of type 'foo'..
console.log("FOO:", data);
});
};
if (browser) {
initSocket();
}
// stores setup and exports omitted..
with svelte-kit preview --host I see the socket creation log message with the socket ID and the same can be seen on the api server where it logs the same ID. The socket works and data is received as expected.
with svelte-kit dev --host however, the log message from socket.on("connect").. is never output and I just see an endless stream of error messages in the browser console from the socket.on("connect_error").. call..
Failed to connect Error: xhr poll error
at XHR.onError (transport.js:31)
at Request.<anonymous> (polling-xhr.js:93)
at Request.Emitter.emit (index.js:145)
at Request.onError (polling-xhr.js:242)
at polling-xhr.js:205
Importantly, there is no attempt to actually contact the server at all. The server never receives a connection request and wireshark/tcpdump confirm that no packet is ever transmitted to 192.168.1.5:4000
Obviously having to rebuild and re-run preview mode on each code change makes development pretty painful, does anyone have insight as to what the issue is here or suggestions on how to proceed?

I've had a similar problem, I solved it by adding this code to svelte.config.js:
const config = {
kit: {
vite: {
resolve: {
alias: {
"xmlhttprequest-ssl": "./node_modules/engine.io-client/lib/xmlhttprequest.js",
},
},
},
},
};
The solution was provided by this comment from the vite issues.

Related

socket.emit not executing inside function in sveltekit

I am having problems with SvelteKit and SocketIO. I'm connecting to a NestJS back-end with a default SocketIO gateway and connecting works fine, but executing a socket.emit inside a function fails to trigger entirely. Not sure if this is SocketIO or SvelteKit related, but executing an emit outside of a function works. Here is my code snippet.
<script>
import io from 'socket.io-client';
let socket = io('http://localhost:5000');
socket.on("connect", () => {
console.log(socket.id);
});
socket.on("messages", (arg) => {
console.log(arg);
});
socket.emit("messages", "executes at load", (err) => {
console.log(err);
});
function onSendMessage() {
console.log('executing function');
socket.emit("messages", "test", (err) => {
console.log(err);
});
}
</script>
<button on:click={onSendMessage}>
Send Message
</button>
In this situation ''executes at load'' is printed to the console because it is emitted and the server sends the response back which the socket.on catches. It also prints the ID of the connection through socket.on("connect"). but it never will print ''test'' if i press the button. Pressing the button does console log the ''executing function''. Tested all functionality on Postman as well and the server works. Executing the function manually directly in the script tag without the button onclick results in the same behaviour of the emit not executing. Anyone has an idea?
After a long time of agony I discovered the problem. I think it has to do with the fact that it was trying to establish an XHR Polling connection on the clientside but not on the SSR side of SvelteKit, and it seems that XHR Polling does not support CORS but websockets do.
All I had to do was specify the transport as ''websocket'' on both the frontend and backend and it works perfectly!

How to set up a socket connection on a strapi server

I am trying to integrate socket.io with strapi. But unfortunately I have been unable to do so without any proper tutorial or documentation covering this aspect.
I followed along with the only resource I found online which is:
https://medium.com/strapi/strapi-socket-io-a9c856e915a6
But I think the article is outdated. I can't seem to run the code mentioned in it without running into tonnes of errors.
Below is my attempt to implement it and I have been trying to connect it through a chrome websocket plugin smart websocket client But I am not getting any response when I try to run the server.
I'm totally in the dark. Any help will be appreciated
module.exports = ()=> {
// import socket io
var io = require('socket.io')(strapi.server)
console.log(strapi.server) //undefined
// listen for user connection
io.on('connect', socket => {
socket.send('Hello!');
console.log("idit")
// or with emit() and custom event names
socket.emit('greetings', 'Hey!', { 'ms': 'jane' }, Buffer.from([4, 3, 3, 1]));
// handle the event sent with socket.send()
socket.on('message', (data) => {
console.log(data);
});
// handle the event sent with socket.emit()
socket.on('salutations', (elem1, elem2, elem3) => {
console.log(elem1, elem2, elem3);
});
});
};
So I found the solution. Yay. I'll put it here just in case anybody needs it.
boostrap.js
module.exports = async () => {
process.nextTick(() =>{
var io = require('socket.io')(strapi.server);
io.on('connection', async function(socket) {
console.log(`a user connected`)
// send message on user connection
socket.emit('hello', JSON.stringify({message: await strapi.services.profile.update({"posted_by"})}));
// listen for user diconnect
socket.on('disconnect', () =>{
console.log('a user disconnected')
});
});
strapi.io = io; // register socket io inside strapi main object to use it globally anywhere
})
};
Found this at: https://github.com/strapi/strapi/issues/5869#issuecomment-619508153_
Apparently, socket.server is not available when the server starts. So you have to make use of process.nextTick that waits for the socket.server to initialize.
I'll also add a few questions that I faced when setting this up.
How do i connect from an external client like nuxt,vue or react?
You just have to connect through "http://localhost:1337" that is my usual address for strapi.
I am using nuxt as my client side and this is how set up my socketio on the client side
I first installed nuxt-socket-io through npm
Edited the nuxt.config file as per it's documention
modules:[
...
'nuxt-socket-io',
...
],
io: {
// module options
sockets: [
{
name: 'main',
url: 'http://localhost:1337',
},
],
},
And then i finally added a listener in one of my pages.
created() {
this.socket = this.$nuxtSocket({})
this.socket.on('hello', (msg, cb) => {
console.log('SOCKET HI')
console.log(msg)
})
},
And it works.
A clean way to integrate third-party services into Strapi is to use hooks. They are loaded once during the server boot. In this case, we will create a local hook.
The following example has worked with strapi#3.6.
Create a hook for socket.io at ./hooks/socket.io/index.js
module.exports = strapi => {
return {
async initialize() {
const ioServer = require('socket.io')(strapi.server, {
cors: {
origin: process.env['FRONT_APP_URL'],
methods: ['GET', 'POST'],
/* ...other cors options */
}
})
ioServer.on('connection', function(socket) {
socket.emit('hello', `Welcome ${socket.id}`)
})
/* HANDLE CLIENT SOCKET LOGIC HERE */
// store the server.io instance to global var to use elsewhere
strapi.services.ioServer = ioServer
},
}
}
Enable the new hook in order for Strapi to load it - ./config/hook.js
module.exports = {
settings: {
'socket.io': {
enabled: true,
},
},
};
That's done. You can access the websocket server inside ./config/functions/bootstrap.js or models' lifecycle hooks.
// ./api/employee/models/employee.js
module.exports = {
lifecycles: {
async afterUpdate(result, params, data) {
strapi.services.ioServer.emit('update:employee', result)
},
},
};
For those who are looking the answer using Strapi version 4
var io = require("socket.io")(strapi.server.httpServer)

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.

Uncaught (in promise) DOMException When Initiating pushManager.subscribe

I'm trying to add push messaging to my service worker and facing issue that is eluding me since last night.
In my main HTML file, I have the following -
<script>
if('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/service-worker.js', {scope: '/pwa/'}).then(registration => {
console.log('Service Worker Registered: ', registration);
registration.pushManager.subscribe({userVisibleOnly:true});
});
})
}
</script>
I do get "Service Worker Registered" message on the console. Which means the registration is successful. Chrome however follows it with following line that doesn't say anything about the error -
Uncaught (in promise) DOMException (index):1
Clicking on the (index):1 takes me to the top of corresponding page /pwa/, and highlights the <!DOCTYPE html>.
It does not give me any meaningful information to investigate the issue further.
Would appreciate if you could guide me in fixing this issue. I'll paste the rest of my code and setup below.
Backend framework: Laravel.
Entry in my webpack.mix.js
const workboxPlugin = require('workbox-webpack-plugin');
mix.webpackConfig({
plugins: [
new workboxPlugin.InjectManifest({
swSrc: 'public/service-worker-offline.js', // more control over the caching
swDest: 'service-worker.js', // the service-worker file name
importsDirectory: 'service-worker-assets' // have a dedicated folder for sw files
})
],
output: {
publicPath: '' // Refer: https://github.com/GoogleChrome/workbox/issues/1534
}
});
Entry in my service-worker-offline.js -
workbox.skipWaiting();
workbox.clientsClaim();
// some other entries, followed by
self.addEventListener('push', (event) => {
const title = 'Aha! Push Notifications with Service Worker';
const options = {
'body' : event.data.text()
};
event.waitUntil(self.registration.showNotification(title, options))
});
I look forward to your responses and thank you in advance for your help.
Addendum:
I did further investigation and found out that if I do -
Notification.requestPermission().then(function(permission) {
registration.pushManager.subscribe({userVisibleOnly: true});
})
then the push notification works; but the error still remains. However, the error now points to registration.pushManager.subscribe({userVisibleOnly: true}); line in the JS. What could be the reason?
The DOMException has details that are not always visible. Catch your DOMException, and make sure to log the message to the console. It will generally be much more informative. In my case, the "Registration failed - permission denied" message reminded me that I had blocked all notifications in my chrome settings.
If you are using react, fix serviceWorker.unregister () with serviceWorker.register () in index.js. I solved it like this

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.

Resources