@H_301_1@我正在尝试创建一个websocket客户端 – 服务器应用程序,其中客户端和服务器将在两个不同的实例上运行.
建立
>服务器/后端:在本地主机上运行:9006与angular-fullstack generator包括socket.io
>客户端/前端:在localhost上运行:9007 with angular generator socket.io-client btford.socket-io(AngularJS socket.io bridge)
服务器
注意:不完整的代码,但我认为是相关的.
// ----- socketio.js ----- // When the user connects.. perform this function onConnect(socket) { // When the client emits 'info',this listens and executes socket.on('info',function (data) { console.info('[%s] %s',socket.address,JSON.stringify(data,null,2)); socket.emit('pong','OK!'); }); // Insert sockets below require('../api/thing/thing.socket').register(socket); } socketio.set('origins','http://localhost:9007'); // ----- express.js ----- app.use(function (req,res,next) { res.setHeader('Access-Control-Allow-Origin','http://localhost:9007'); res.setHeader('Access-Control-Allow-Methods','GET,POST,OPTIONS,PUT,PATCH,DELETE'); res.setHeader('Access-Control-Allow-Credentials',true); next(); }); // ----- app.js ----- // Start server server.listen(config.port,config.ip,function () { console.log('Express server listening on %d,in %s mode',config.port,app.get('env')); });
客户
// ----- client app.js angular .module('weldCommentsClientApp',[ 'ngAnimate','ngAria','ngCookies','ngMessages','ngResource','ngRoute','ngSanitize','ngTouch','btford.socket-io' ]) .factory('mySocket',function (socketFactory) { var myIoSocket = window.io.connect('http://localhost:9006'); var mySocket = socketFactory({ ioSocket: myIoSocket }); mySocket.forward('pong'); console.log('mySocket',mySocket); return mySocket; }) // ----- client main.js angular.module('weldCommentsClientApp').controller('MainCtrl',function ($scope,mySocket) { $scope.$on('socket:pong',function (ev,data) { console.log('socket:pong',ev,data); }); mySocket.emit('info'); });
结果
服务器和客户端上没有控制台错误,但是它不起作用,服务器记录以下行的100个:
GET /socket.io/?EIO=3&transport=polling&t=1421488528935-16027 200 2ms
…它看起来像客户端通过HTTP连接,但无法切换到websockets.
有任何想法吗?
更新
这是整个客户端/服务器项目,其中包含README:https://github.com/weld-io/socket.io-client-server-boilerplate中的说明
解决方法
服务器/ app.js中的路径未正确定义
尝试使用’/socket.io’路径,如下所示:
var socketio = require('socket.io')(server,{ serveClient: (config.env === 'production') ? false : true,path: '/socket.io' });
接下来,要选择websockets而不是长轮询,您可以在test-client / scripts / application.js中选择websocket传输
var myIoSocket = window.io.connect('http://localhost:9006',{transports:['websocket']});