Skip to content

Instantly share code, notes, and snippets.

@quangIO
Created January 10, 2018 15:34
Show Gist options
  • Save quangIO/82e1617dcbf9cf9a9f6a8892df8c475b to your computer and use it in GitHub Desktop.
Save quangIO/82e1617dcbf9cf9a9f6a8892df8c475b to your computer and use it in GitHub Desktop.
<template>
<div id="app">
<div class="row flex-center flex-middle">
<label for="msg">Message</label>
<input class="margin" type="text" id="msg" v-model="message">
</div>
<div class="row flex-center">
<button class="paper-btn margin" @click="send">Send</button>
</div>
</div>
</template>
<script>
export default {
name: 'app',
data() {
return {
message: '',
socket: null,
}
},
methods: {
handle(data) {
console.log(data);
let received = JSON.parse(data);
},
send() {
this.socket.send(JSON.stringify({
"type": "MESSAGE",
"payload": {
"content": this.message,
"maskId": 1
}
}));
},
getWebSocketURL() {
if (window.location.port === '3333') {
return 'ws://localhost:8000/ws/123';
}
return ((window.location.protocol === 'https:') ? 'wss://' : 'ws://') + window.location.host + '/ws/' +
this.$router.currentRoute.query['room'];
},
},
created() {
if (this.socket) this.socket.close();
console.log(this.$router.currentRoute.query);
this.socket = new WebSocket(this.getWebSocketURL());
this.socket.onclose = function (evt) {
let explanation = "";
if (evt.reason && evt.reason.length > 0) {
explanation = "reason: " + evt.reason;
} else {
explanation = "without a reason specified";
}
console.log("Disconnected with close code " + evt.code + " and " + explanation);
};
let vm = this;
this.socket.onmessage = function (event) {
vm.handle(event.data.toString());
};
}
}
</script>
@qq476649388
Copy link

qq476649388 commented Jan 11, 2018

Chinese people live you a message: 你这个例子不错。非常好。能不能交流下啊。有QQ没。From china shenzhen .

@iamziyue
Copy link

这个对我帮助太大了,原来原生的也不是很复杂嘛。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment