先上實作結果(免費的機器人真的是一言難盡)

需要注意的點
- 需要處理開發環境的跨域問題、見代碼
- 由于服務器使用了https協議,所以客戶端需要用wss,因為我用nginx進行https的轉發,因此也需要在nginx上做同步配置(配置在下面)
- 因為是點對點聊天,因此不是廣播形式,用steamUsers 來保存每個鏈接
實作步驟
服務端
koa、http、socket.io等組件的引入及注冊
const Koa = require('koa')
const app = new Koa()
const router = require('./router/index.js');
var BodyParser = require('koa-bodyparser');
const axios = require('axios');
var http = require('http').Server(app);
const io = require("socket.io")(http, {
// 處理跨域問題
allowEIO3: true,
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
global.cache = {};
const bodyparser = new BodyParser();
app.use(bodyparser);
app.use(router.routes());
app.use(router.allowedMethods());
const steamUsers = {};
io.on('connection', function(socket) {
steamUsers[socket.id] = socket;
socket.on('chat message', function(msg) {
oneCharts(msg, socket.id)
});
});
const oneCharts = (msg, id) => {
axios.get(`http://api.tianapi.com/txapi/robot/index`, {
params: {
question: msg,
key: '機器人key',
mode: 1
}
}).then(response => {
if (response.data.code === 200) {
steamUsers[id].emit('chat message', response.data.newslist[0]);
} else {
steamUsers[id].emit('chat message', '哦豁,網路出錯啦');
}
}).catch(error => {
steamUsers[id].emit('chat message', '哦豁,網路出錯啦');
});
}
http.listen(8010);
客戶端(這里使用的vue,各自修改即可)
1、引入socket.io插件
import io from 'socket.io-client';
2、簡單的注冊、發送邏輯
注:本地開發是本地node起的服務,因此在url上做了個判斷,根據自己需求修改,性能問題記得銷毀服務
mounted() {
this.init()
},
methods: {
init() {
const _this = this
let urls = process.env.NODE_ENV === 'development' ? 'ws://127.0.0.1:8010':'wss://域名'
this.socket = io(urls)
this.socket.on('connection', function(socket) {
});
this.socket.on('chat message', async function(msg) {
await _this.list.push({ label: msg.reply, isOwn: false, img: auth })
Array.from(document.getElementsByClassName('style'))[0].scrollIntoView();
});
},
async onSearch() {
this.list.push({ label: this.keyWord, isOwn: true, img: auth })
await this.socket.emit('chat message', this.keyWord);
this.keyWord = ''
Array.from(document.getElementsByClassName('style'))[0].scrollIntoView();
},
},
beforeDestroy() {
this.socket.close()
}
nignx配置
server
{
listen 443 ssl;
server_name 域名;
ssl_certificate 你的證書crt;
ssl_certificate_key 你的證書key;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;
location /socket.io/ {
proxy_pass http://127.0.0.1:8010;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection “Upgrade”;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
}
location ~ .*\.(js|css|ico|png|jpg|eot|svg|ttf|woff|html|txt) {
root /mnt/web-os/person-demo/dist/;
index index.html index.htm index.php font.html;
}
location /api/ {
proxy_pass http://127.0.0.1:8899/;
}
}
server{
listen 80;
server_name 域名;
return 301 https://$server_name$request_uri;
}
include /www/server/panel/vhost/nginx/*.conf;
}
以下部分即為處理socket.io https代理的問題
location /socket.io/ {
proxy_pass http://127.0.0.1:8010;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection “Upgrade”;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/293320.html
標籤:其他
上一篇:搭建Nginx正向代理服務
下一篇:容器|Docker基礎命令
