基于socket.io +koa2 +天行机器人 实现简单人机实时通讯(nginx处理socket.io https代理问题)

Posted 微若年华ヽ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于socket.io +koa2 +天行机器人 实现简单人机实时通讯(nginx处理socket.io https代理问题)相关的知识,希望对你有一定的参考价值。

先上实现结果(免费的机器人真的是一言难尽)

需要注意的点

  • 需要处理开发环境的跨域问题、见代码
  • 由于服务器使用了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;
	}

以上是关于基于socket.io +koa2 +天行机器人 实现简单人机实时通讯(nginx处理socket.io https代理问题)的主要内容,如果未能解决你的问题,请参考以下文章