如何修复浏览器同步& socket.io冲突?

时间:2016-12-03 05:14:39

标签: socket.io aurelia browser-sync aurelia-cli gulp-browser-sync

我似乎与browser-sync中使用的套接字以及我想要与socket.io一起使用的套接字发生冲突。我通过browser-sync任务(gulp默认项目附带)使用Aurelia CLI。发生的情况是只有browser-sync套接字似乎有效,而主要在服务器端使用的socket.io完全未读。我确实找到了解决问题的GitHub issue #71,还有其他Github issue #241,它们都提到了命名空间的使用。然而,我尝试了一些差异,即使它们运行时出现错误,也无法解决我的任何问题。

我主要在Gulp项目中使用browser-sync Aurelia CLI,而后端NodeJS使用Koa。版本socket.io@1.6.0browser-sync@2.13.0使用的端口用于前端:4000,后端:5000。

这是一个文件列表

Gulp - run.js

import gulp from 'gulp';
import browserSync from 'browser-sync';
import historyApiFallback from 'connect-history-api-fallback/lib';
import project from '../aurelia.json';
import build from './build';
import {CLIOptions} from 'aurelia-cli';
import url from 'url';
import proxy from 'proxy-middleware';

var portBackEnd = 5000;
var portFrontEnd = 4000;

var proxyOptionsAccessControl = function(req,res, next){
      res.setHeader('Access-Control-Allow-Origin', '*');
      next();
};

var proxyOptionsApiRoute = url.parse(`http://localhost:${portBackEnd}/api`);
    proxyOptionsApiRoute.route = '/api';

var proxyOptionsAuthRoute = url.parse(`http://localhost:${portBackEnd}/auth`);
    proxyOptionsAuthRoute.route = '/auth';

function log(message) {
  console.log(message); //eslint-disable-line no-console
}

function onChange(path) {
  log(`File Changed: ${path}`);
}

function reload(done) {
  browserSync.reload();
  done();
}

let serve = gulp.series(
  build,
  done => {
    browserSync({
      online: false,
      open: false,
      port: portFrontEnd,
      notify: true,
      logLevel: 'silent',
      server: {
        baseDir: ['.'],
        middleware: [
          proxyOptionsAccessControl,
          proxy(proxyOptionsApiRoute),
          proxy(proxyOptionsAuthRoute)
        ]
      },
      socket: {
        domain: 'localhost:4000',
        namespace: '/browsersync'
      }
    }, function(err, bs) {
      let urls = bs.options.get('urls').toJS();
      log(`Application Available At: ${urls.local}`);
      log(`BrowserSync Available At: ${urls.ui}`);
      done();
    });
  }
);

let refresh = gulp.series(
  build,
  reload
);

let watch = function() {
  gulp.watch(project.transpiler.source, refresh).on('change', onChange);
  gulp.watch(project.markupProcessor.source, refresh).on('change', onChange);
  gulp.watch(project.cssProcessor.source, refresh).on('change', onChange);
};

let run;

if (CLIOptions.hasFlag('watch')) {
  run = gulp.series(
    serve,
    watch
  );
} else {
  run = serve;
}

export default run;

使用Socket.io-Client和Aurelia(前端)

import io from 'socket.io-client';

var socket = io('http://localhost:5000');
// also tried with a namespace instead
//var socket = io('/todo-socket');

// ...

socket.on("todo_update", data => {
  let pos = arrayFindObjectIndex(this.items, 'id', data.id);
  if(pos >= 0) {
     this.items.splice(pos, 1, data);
     this.itemDoneCount = this.items.filter(x => x.completed).length;
   }
});

NodeJS with Koa(后端)

// Middlewares
const app = require('koa')();
const serve = require('koa-static');
const api = require('koa-router')();
const assertTimeout = require('co-assert-timeout');
const http = require('http');
const server = require('http').createServer(app.callback());
const io = require('socket.io')(server);

// or without namespace: io.sockets.on("connection", function(socket) {
var tsp = io.of('/todo-socket');
tsp.on("connection", function(socket) {
  console.log('A new WebSocket client connected with ID: ' + socket.client.id);
})
.error(function(err){
  console.log("Changefeeds Failure: ", err);
  return null;
});

socket.on('disconnect', function(data) {
  console.log('A WebSocket client disconnnected with ID: ' +      socket.client.id);
  return null;
});

我尝试使用和不使用命名空间,但似乎没有改变任何东西。我提到browser-sync - socket option

修改

通过测试更多,实际上服务器端的socket.io似乎根本不起作用。它不会从服务器输出console.log('connected with ID: ' + socket.client.id),但它也不会显示或抛出任何错误。服务器端的代码曾用于WebPack,因此我认为它与browserSync冲突有关。

2 个答案:

答案 0 :(得分:1)

经过几天后,我开始工作了。我必须在browserSync选项中以及客户端(Aurelia)中的两个不同位置更改命名空间,其中我使用另一个必须是不同命名空间的套接字。最后,必须使用NodeJS Koa调用io.of('/clientNamespace')

重要提示,请注意browserSync和客户端命名空间必须使用完整的URL声明:port + namespace(例如: http://localhost:4000/namespaceBs),在服务器端,命名空间仅与没有URL的名称一起使用(例如:/namespaceClient)。

如果您有疑问,我将其称为todoSocket,因为它是TODO App

所以为了简短起见,我更改了以下代码:

Gulp - run.js

let serve = gulp.series(
  build,
  done => {
    browserSync({
      online: false,
      open: false,
      port: portFrontEnd,
      notify: true,
      logLevel: 'silent',
      server: {
        baseDir: ['.'],
        middleware: [
          proxyOptionsAccessControl,
          proxy(proxyOptionsApiRoute),
          proxy(proxyOptionsAuthRoute)
        ]
      },
      socket: {
        namespace: `http://localhost:4000/bs` // <<<< HERE >>>>
      }
    }, function(err, bs) {
      let urls = bs.options.get('urls').toJS();
      log(`Application Available At: ${urls.local}`);
      log(`BrowserSync Available At: ${urls.ui}`);
      done();
    });
  }
);

使用Socket.io-Client和Aurelia(前端)

import io from 'socket.io-client';

var socket = io('http://localhost:5000/todo-socket'); // <<<< HERE >>>>

NodeJS with Koa

const http = require('http');
const server = http.createServer(app.callback());
const io = require('socket.io')(server);

// Load config for RethinkDB and koa
const config = require("./config");

// attach on the todo-socket namespace, only the name (not the full URL)
var todoSocket = io.of('/todo-socket');         // <<<< HERE >>>>
todoSocket.on("connection", function(socket) {  // <<<< AND HERE >>>>
  console.log('A new TODO WebSocket namespace client connected with ID: ' + socket.client.id);
});

答案 1 :(得分:1)

对于本文中发生的其他任何人,以上内容均不适用于他们。我在配置中设置了proxy

proxy: {
  target: `${protocol}://localhost:${SERVER__PORT}`,        
},

最终使两个套接字一起工作的解决方案是简单地添加ws

proxy: {
  target: `${protocol}://localhost:${SERVER__PORT}`,
  ws: true,
},