Answer the question
In order to leave comments, you need to log in
JSON parsing in worker?
Of the answers only from 2015 in Google.
Does it make sense to make a separate websocket worker? I communicate with the server by spitting JSON on it.
The question is: is parsing jsona in a separate thread leveled due to copying objects when passing from the worker and back? Or is there such a design?
// App.vue
mounted() {
this.$store.state.socketWorker = new Worker('/js/socketWorker.js');
this.$store.state.socketWorker.addEventListener('message', ({ data }) => !this.$store._mutations[data.a] || this.$store.commit(data.a, data));
};
// Воркер
var ws = new WebSocket('wss://someaddr');
ws.onmessage = ({data}) => {
try { data = JSON.parse(data); } catch(e) { return; };
self.postMessage(data);
};
self.addEventListener('message', ({ data }) => {
if (!ws || ws.readyState !== 1) return;
let msg = '';
try { msg = JSON.stringify(data); } catch(e) { return; };
ws.send(msg);
});
Answer the question
In order to leave comments, you need to log in
I would prefer the department in favor of no worker. This approach only works if you have very large JSONs. So large or so many that the time to process them is noticeable to the naked eye.
If this is not the case, then it would be more convenient for me to keep the socket in the main thread. This will enable all components to independently subscribe to different events. Something like this:
// socketFactory.js
let ws = null
export function getSocket() {
if (!ws) ws = new WebSocket('wss://someaddr');
return ws
}
// SomeComponent.vue
import {getSocket} from 'socketFactory.js'
const ws = getSocket()
export default defineComponent({
created() {
ws.onmessage(message => {
if ( ... ) {
// Делаем что-то с сообщением
this.onMessageHandled(message)
}
})
},
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question