nathantsoi / vue-native-websocket Goto Github PK
View Code? Open in Web Editor NEWnative websocket with vuex integration
native websocket with vuex integration
Hi.
I am having problems using the socket after it is closed and (successfully) reconnected.
Although after the reconnect I get the ONOPEN event, the readyState of the socket is 3, meaning CLOSED or CLOSING.
I am using the sockets with the Vuex store, and I am assigning the Vue.prototype.$socket to store.$socket, to be able to access the socket in the store.
Sample of the code
// socket mutations
SOCKET_ONOPEN (state, event) {
state.socket.isConnected = true
console.log('connected ...', this.$socket)
},
The first time the code is ran the socket is ok, in readyState 1, after reconnect the readyState remains 3
Any ideas?
together with onmessage
handler I want to define onsend
handler. Is it possible?
var vm = this;
this.$options.sockets.onmessage = function (message) {
vm.loading = false;
vm.listen(message);
};
this.$options.sockets.onsend = function () {
vm.loading = true;
}
Vue.use(VueNativeSock, 'ws://localhost:9090')
Plugin can't install over and over times , so How can I change the socket url.
Hello,
In Main.js file you use Proxy object and it's causes that my app not work in IE 11, because in IE 11 there is no Proxy object.
How can I resolve it? Maybe some Polyfill?
I have an issue.
When i try to send a message i get the following error:
Uncaught TypeError: Cannot read property '$socket' of undefined
this.$socket.send('some data')
Seem not to work? Or am i doing it wrong?
It does work outside the store... But it would be handy to call it inside a store actions to send it of to the server. Can I call it somehow there?
1.0版本 可以触发 mutations onopen 2.0版本触发 不了
Hello!
Please, tell me, how to subscribe to a channel?
Thanks!
The WebSocket that is created in the Observer tests the connection url and must contain both schema and authority, I can not pass a relative path like "/ws-endpoint". Therefore I can not use the webpack dev server to proxy the call although it is able to deal with the ws protocol, see https://github.com/chimurai/http-proxy-middleware#options. Is there any way to deal with this?
import VueNativeSock from 'vue-native-websocket'
Vue.use(VueNativeSock, 'ws://localhost:3000', {store: store, format: 'json'})
vuex.esm.js?358c:383 [vuex] unknown mutation type: SOCKET_ONMESSAGE
this mutations is defined in the sub module socket:
/socket/mutations.js
SOCKET_ONMESSAGE (state, message) {
for (var property in message) {
console.log(property + ' = ' + message[property])
}
}
In index.js:
import socketModule from '@/store/modules/socket
Vue.use(Vuex)
export const store = new Vuex.Store({
modules: {
socket: socketModule
},
If the mutations is defined in index.js everything works
when i try to connect with server thourgh socket i get this error in console i dont know where i am going wrong..
'ws://localhost:8888/' failed: Connection closed before receiving a handshake response
How would be the best way to mock sockets with this library in order to have tests and to develop without the need of the actual WS peer sending and receiving messages?
Hi,
Line 3 in ./src/Emitter.js is giving me error on Android 4.4.
this.listeners = new Map()
Is there a polyfill or another way than using "new Map()" so it works on Android 4.4?
Thanks !
How would I do a simple login with this package. What is the preferred way?
computed: {
...mapGetters([
'user',
])
},
watch: {
user(user) {
if (user) {
window.location = '/home';
}
},
},
methods: {
login() {
this.$socket.sendObj({ type: 'login', user: this.username, password: this.password });
this.username = '';
this.password = '';
}
},
const actions = {
[LOGIN]({ commit }, { user, password }) {
return new Promise((resolve) => {
// send login request with user and password
this.$socket.sendObj({ type: 'login', user, password });
// wait for answer. maybe watch mutations change?
waitForAnswer('auth:login', ({ user }) => {
resolve(user);
});
});
}
};
How do I change the websocket url string? The component needs to connect to a different websocket url depending on the current url.
Here is an example of my component:
<script>
import VueNativeSock from 'vue-native-websocket'
Vue.use(VueNativeSock, 'ws://myserver:8080/logs?id=' + this.$route.params.id);
export default {
...
}
</script>
So if the current url is http://example/results/1234, then I need to open the connection to ws://myserver:8080/logs?id=1234.
SOCKET_ONMESSAGE (event, message) {
should be
SOCKET_ONMESSAGE (state, message) {
I'm using this module inside created() component method, but when I destroy the component always got this error message:
Error in beforeDestroy hook: "TypeError: Cannot read property 'sockets' of undefined"
Here is my code:
<template>
...
</template>
<script>
export default {
data(){
return {
productos: [],
}
},
created() {
// listener
this.$options.sockets.onmessage = (messageEvent) => {
// logic here
};
},
destroyed(){
console.log('destroyed');
},
beforeDestroy(){
console.log('beforeDestroy');
}
}
</script>
<style>
</style>
Error stack: https://imgur.com/a/krORJ
After reconnected websocket, this.$socket.send , can not send message, chrome console Error message :"WebSocket is already in CLOSING or CLOSED state" 。in other words , the "socket Instance" in vuex's state is not updated. still the previous one.
How exactly can I listen to events if I do not have a store?
I've tried this in my created method if my main component, but it's not firing:
this.$options.sockets.SOCKET_ONMESSAGE = (data) => {console.log("a message")}
在main.js中定义的socket链接后,如果链接发生重连,那么在.vue组件中,使用this.$socket.send()将报错
In some case , I need to monitor different websocket url when I change vue router or click some button. The websocket url in the “main.js” whether or not dynamic change
Hi,
I have to load vue-native-websocket throught script like
<script src="{% static 'js/vue.js' %}"></script>
<script src="{% static 'js/vue-native-websocket.min.js' %}"></script>
<script src="{% static 'js/vue_components/OrdersCurrent.js' %}"></script>
here's my OrdersCurrent.js
Vue.use(VueNativeSock, 'wss://localhost/ws/current-orders/1', {
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 3000,
format: 'json',
});
var app = new Vue({
el: '#orders-current-app',
delimiters: ['{*', '*}'],
created: function () {
var vm = this;
this.$options.sockets.onmessage = function (data) {
vm.messageReceived(data);
}
},
data: {
message: 'hi Vue!'
},
methods: {
sendMessage: function(event) {
message = event.target.value;
this.$socket.sendObj({message: message});
event.target.value = ''
},
receiveMessage: function(websocketMessage) {
var data = JSON.parse(websocketMessage.data);
this.messages.push(data.message);
}
}
});
Looks like Vue.use
not working in this case. I got the following error
vue.js:597 [Vue warn]: Error in created hook: "TypeError: Cannot set property 'onmessage' of undefined"
(found in <Root>)
warn @ vue.js:597
logError @ vue.js:1739
globalHandleError @ vue.js:1734
handleError @ vue.js:1723
callHook @ vue.js:2923
Vue._init @ vue.js:4617
Vue @ vue.js:4716
(anonymous) @ OrdersCurrent.js:8
vue.js:1743 TypeError: Cannot set property 'onmessage' of undefined
at Vue.created (OrdersCurrent.js:13)
at callHook (vue.js:2921)
at Vue._init (vue.js:4617)
at new Vue (vue.js:4716)
at OrdersCurrent.js:8
if the message received does not have a namespace then the path looks like /someaction instead of just someaction
Broken cable is not supported
Is there a way to send websocket messages from within my Vuex actions?
I've been struggling with this for a while and was hoping the update would sort it but I'm still having the same problem and perhaps I'm missing some understanding.
In main.js:
import Vue from 'vue';
import VueNativeSock from 'vue-native-websocket';
import App from './App';
import router from './router';
Vue.use(VueNativeSock, process.env.WEBSOCKET_ADDR, {
format: 'json',
reconnection: true, // (Boolean) whether to reconnect automatically (false)
reconnectionAttempts: 5, // (Number) number of reconnection attempts before giving up (Infinity),
reconnectionDelay: 3000, // (Number) how long to initially wait before attempting a new (1000)
});
/* eslint-disable no-new */
new Vue({
components: { App },
router,
template: '<App/>',
}).$mount('#app');
In App.vue (minimal):
<script>
export default {
name: 'app',
created() {
this.$socket.onopen = () => {
console.log('connected');
};
this.$socket.onclose = () => {
console.log('disconnected');
};
},
};
</script>
If I start with the WS server is running, it's connected, when I kill the server process, disconnected.
Then I start the server again, I would expect it to reconnect. Am I wrong in thinking this? Is my implementation wrong?
If after onopen event, server close connection (onclose event), websocket going to infinite recconection. It causes because recconnection counter cleared after onopen event.
Can someone please point me to the proper way to disconnect - I suppose $socket.close() should be used. But if reconnect is enabled - how to disable it. Thank you.
Hi there,
Is there a way to get the sec-websocket-key? or some kind of unique id?
Thanks,
Danny
When a page where a vue component is using the vue native websocket is loaded, it connects and works without any problem. After switching to another page and coming back by using vue router, the websocket do not reconnect.
If we switch the network connection off then it changes the states to ONCLOSE and socket gets disconnected. But its not coming back to ONOPEN when network connection comes back?
When I want to use namespaces, how can I handle the SOCKET_* mutations?
I got namespaced messages to work, but I am getting messages like [vuex] unknown mutation type: SOCKET_ONOPEN
.. Where do I store the SOCKET_*
mutations?
Now in build (https://raw.githubusercontent.com/nathantsoi/vue-native-websocket/master/dist/build.js) there is Object.seal(this.$options.sockets)
using
IE11 doesn't know what it is & will throw error. I think need to include polyfill for Object.seal or mention about it in readme
Got the following error when run webpack:
Hash: d1a9ada4be8154684b8b
Version: webpack 3.6.0
Time: 158ms
Asset Size Chunks Chunk Names
build.js 7.63 kB 0 [emitted] main
build.js.map 8.16 kB 0 [emitted] main
[0] ./src/Emitter.js 1.15 kB {0} [built]
[1] multi ./src/Main.js 28 bytes {0} [built]
[2] ./src/Main.js 1.19 kB {0} [built]
[3] ./src/Observer.js 1.44 kB {0} [built]
ERROR in build.js from UglifyJs
Unexpected token: name (Emitter) [build.js:81,6]
How can I set the binaryType?
I need to do something like this?
ws.binaryType = 'arraybuffer';
。
Hi there,
this is more like a question than a bug.
I just wanted to integrate this in my NuxtJs store and ran into the following error
NuxtJs is forcing you to export the store as a function and I dont know when the store is available for the client (this might be the problem) really because its this Nuxt Server/Client thingy.
In my plugin its defined like this:
import Vue from 'vue'
import VueNativeSocket from 'vue-native-websocket'
import store from '~/store'
console.log(store)
Vue.use(VueNativeSocket, process.env.WS_URL, {
store: store,
reconnection: true,
reconnectionDelay: 1000,
format: 'json'
})
the console.log(store) returns this
ƒ Store() {
return new __WEBPACK_IMPORTED_MODULE_0_vuex__["default"].Store({
state: {},
getters: {},
mutations: {},
actions: {}
});
}
Please tell me whether it is possible using vue-native-websocket to simultaneously use two web sites with different url. I tried to create two different components for each of the two websocket, but they do not work. And if I leave only one websocket then everything works fine.
Please, help...
In the usage i get an eslint error on ws.WS_RECONNECT
and ws.WS_RECONNECT_ERROR
perhaps the global WebSocket object can be used here instead?
I want to separate onopen events for each vue component. Now I see alerts with 1 and 2 two times.
Is there a way to avoid this duplication?
Vue.use(VueNativeSock.default, wsPath, {
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 3000,
format: 'json',
});
var app1 = new Vue({
created: function () {
var vm = this;
this.$options.sockets.onmessage = function (message) {
vm.listen(message);
};
this.$options.sockets.onopen = function () {
alert(1);
}
}
});
var app1 = new Vue({
created: function () {
var vm = this;
this.$options.sockets.onmessage = function (message) {
vm.listen(message);
};
this.$options.sockets.onopen = function () {
alert(2);
}
}
});
Only install [email protected] with npm command
npm install vue-native-websocket@latest --save
Please fix
Thanks
vue-native-websocket/src/Observer.js
Line 56 in 07328e1
Hi,
is there a way to reconnect the WS after a disconnection (for example after a reboot of the server)?
Thanks
Can we get some working examples. Both with and without using store?
Can vue-native-websocket be used in combination with JSON Web Token for authentication?
Is it possible to create simultaneous websocket connections to two different servers? For redundancy purposes, I want to create two connections at once and then use which ever one connects first (in case one of the two servers is offline). I'm using ConnectManually = true and the VUEX store to handle all communication. If dual is not an option, is it at least possible to dynamically change the URL that ws.$connect is going to use?
How can I connect and close at any time and change url?
How can i use onmessage
or onopen
in my Vue component? I have vue-native-websocket and vuex already setup. I know i should use this code https://github.com/nathantsoi/vue-native-websocket#dynamic-socket-event-listeners but where?
I do not know wether this is desired behavior, but i use namespaced stores und vue-native-websocket is not able to call actions accordingly.
It is because you do not include the namespace when generating the action:
if (msg.mutation) { target = [msg.namespace || '', msg.mutation].filter((e) => !!e).join('/') } else if (msg.action) { method = 'dispatch' target = msg.action }
In my opinion this is a bug and i could create a pull-request if you want to?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.