Vue+Socket.io這個輪子已經有不少人造過了,爲了避免重複造輪子,我將本項目以三階段實現(你們能夠在github中的Releases查看):javascript
但願能給你們一個漸進學習的經驗。
本項目地址:github.com/spiritree/v…
若是喜歡的話,歡迎Star&Fork,謝謝你們html
npm install -g vue-cli
前端
vue init webpack my-project
vue
vue init ElemeFE/webpack-typescript my-project
(感謝餓了麼分享的TypeScript的模板)java
這樣就在當前目錄下建立了完整的工程模板node
在Server端(Express)webpack
import * as socketIo from 'socket.io'
this.io.on('connection', (socket: any) => {
socket.on('sendMessage', (data: any) => {
this.io.emit('boardcastMessage', data)
})複製代碼
在Client端(Vue)nginx
<script lang="ts">
/// <reference path="../../socket.io.d.ts" />
export default Vue.extend({
mounted() {
socket.on('boardcastMessage', (data: any) => {
this.$store.dispatch('sendMessage', { data })
})
}
})複製代碼
Server端經常使用API:git
socket.emit()
:向創建該鏈接的客戶端發送消息es6
socket.on()
:監聽客戶端發送信息
io.sockets.emit()
:向全部客戶端廣播
Client端經常使用API:
socket.emit()
:向服務端發送消息
socket.on()
:監聽服務端發來的信息
關於TypeScript的基本知識,能夠直接看xcatliu整理的教程,簡單易懂,有Java/C#基礎就可快速上手。
TypeScript 入門教程
也可用官方插件vue-class-component
本項目參考vue init ElemeFE/webpack-typescript my-project
先添加聲明文件(Vue全家桶自帶就不須要了)
本項目用到Express和Socket.io
npm install typescript --save-dev
npm i ts-loader --save-dev
{
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
appendTsSuffixTo: [/\.vue$/],
}
},
],
}
}複製代碼
socket.io.d.ts(爲了編譯經過)
declare namespace socket {
var on: any;
var emit: any;
var data: any;
}複製代碼
npm install gulp --save-dev
npm install gulp-typescript --save-dev
npm install @types/express --save-dev
npm install @types/socket.io --save-dev
├── app.js
├── gulpfile.js
├── register.js
├── src
│ ├── type-app.ts
│ └── type-register.ts
├── tsconfig.json
├── type-app.js
└── type-register.js
{
"include": [
"src/*.ts"
],
"compilerOptions": {
"noImplicitAny": true,
"lib": ["es6"],
"target": "es5",
"outDir": ""
}
}複製代碼
var gulp = require("gulp");
var ts = require("gulp-typescript");
var tsProject = ts.createProject("tsconfig.json");
gulp.task("build", function () {
return tsProject.src()
.pipe(tsProject())
.js.pipe(gulp.dest(""));
});複製代碼
Linux+Nginx的組合,能夠一鍵部署虛擬主機
OneinStack
部署的遇到的坑
github.com/socketio/so…
Error during WebSocket handshake: Unexpected response code: 400
在nginx.conf添加
location / {
proxy_pass http://localhost:8989;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}複製代碼
預覽地址:app.spiritree.me/
Github地址:github.com/spiritree/v…
git clone https://github.com/spiritree/vue-socket.io-chat.git
npm install
npm run server
npm install
cd server
gulp build
npm run tsserver
瀏覽器訪問 http://localhost:8989
如遇在線列表不一樣步,刷新重進便可