Phone 差距 + socket.io + heroku

Phone gap + socket.io + heroku

我有一个应用程序调用托管在 heroku 上的 socket.io 服务器。 当我使用命令 "phonegap serve" 在我的手机 (android) 上启动我的应用程序时,出现此错误:

[phonegap] Proxy error for url: myserverheroku:3000/socket .io/?EIO=3&transport=polling&t=1421696372422-2 undefined [phonegap] ECONNREFUSED myserverheroku:3000/socket.io/?EIO =3&transport=polling&t=1421696372422-2

你能帮忙吗?

(对不起我的英语,我是法语)

server.js 文件:

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
    res.sendfile('index.html');
});

http.listen(process.env.PORT || 3000);

io.on('connection', function (socket) {
  socket.emit('news', { message: 'Hello world' });
});

app.js 文件:

var socket = io.connect('http://star-wars-bluff.herokuapp.com');
socket.on('news', function (data) {
    document.getElementById('welcomeMsg').innerHTML = data.message;
});

index.html 文件:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="msapplication-tap-highlight" content="no" />
        <!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="css/main.css" />
        <title>Star Wars Bluff</title>
    </head>
    <body>
        <div class="jumbotron text-center">
            <h1>Star Wars Bluff</h1>
        </div>
        <div class="container">
            <div id="welcomeMsg"></div>
        </div>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script><!-- load angular -->
        <script type="text/javascript" src="cordova.js"></script>
        <script src="http://star-wars-bluff.herokuapp.com/socket.io/socket.io.js"></script>
        <script type="text/javascript" src="js/app.js"></script>
    </body>
</html>

config.xml 文件:

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.heroku.star-wars-bluff" version="1.0.0" versionCode = "10" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>Star Wars Bluff</name>
    <description>
        Le poker des cafards version Star Wars
    </description>
    <author email="contact@labo-web.fr" href="http://labo-web.fr">
        Labo web
    </author>
    <content src="index.html" />
    <preference name="permissions" value="none" />
    <preference name="phonegap-version" value="3.5.0" />
    <preference name="orientation" value="default" />
    <preference name="target-device" value="universal" />
    <preference name="fullscreen" value="true" />
    <preference name="webviewbounce" value="true" />
    <preference name="prerendered-icon" value="true" />
    <preference name="stay-in-webview" value="false" />
    <preference name="ios-statusbarstyle" value="black-opaque" />
    <preference name="detect-data-types" value="true" />
    <preference name="exit-on-suspend" value="false" />
    <preference name="show-splash-screen-spinner" value="true" />
    <preference name="auto-hide-splash-screen" value="true" />
    <preference name="disable-cursor" value="false" />
    <preference name="android-minSdkVersion" value="7" />
    <preference name="android-installLocation" value="auto" />
    <!-- <gap:plugin name="org.apache.cordova.battery-status" />
    <gap:plugin name="org.apache.cordova.camera" />
    <gap:plugin name="org.apache.cordova.media-capture" />
    <gap:plugin name="org.apache.cordova.console" />
    <gap:plugin name="org.apache.cordova.contacts" />
    <gap:plugin name="org.apache.cordova.device" />
    <gap:plugin name="org.apache.cordova.device-motion" />
    <gap:plugin name="org.apache.cordova.device-orientation" />
    <gap:plugin name="org.apache.cordova.dialogs" />
    <gap:plugin name="org.apache.cordova.file" />
    <gap:plugin name="org.apache.cordova.file-transfer" />
    <gap:plugin name="org.apache.cordova.geolocation" />
    <gap:plugin name="org.apache.cordova.globalization" />
    <gap:plugin name="org.apache.cordova.inappbrowser" />
    <gap:plugin name="org.apache.cordova.media" />
    <gap:plugin name="org.apache.cordova.network-information" />
    <gap:plugin name="org.apache.cordova.splashscreen" />
    <gap:plugin name="org.apache.cordova.vibration" /> -->
    <icon src="icon.png" />
    <icon gap:platform="android" gap:qualifier="ldpi" src="www/res/icon/android/icon-36-ldpi.png" />
    <icon gap:platform="android" gap:qualifier="mdpi" src="www/res/icon/android/icon-48-mdpi.png" />
    <icon gap:platform="android" gap:qualifier="hdpi" src="www/res/icon/android/icon-72-hdpi.png" />
    <icon gap:platform="android" gap:qualifier="xhdpi" src="www/res/icon/android/icon-96-xhdpi.png" />
    <icon gap:platform="blackberry" src="www/res/icon/blackberry/icon-80.png" />
    <icon gap:platform="blackberry" gap:state="hover" src="www/res/icon/blackberry/icon-80.png" />
    <icon gap:platform="ios" height="57" src="www/res/icon/ios/icon-57.png" width="57" />
    <icon gap:platform="ios" height="72" src="www/res/icon/ios/icon-72.png" width="72" />
    <icon gap:platform="ios" height="114" src="www/res/icon/ios/icon-57-2x.png" width="114" />
    <icon gap:platform="ios" height="144" src="www/res/icon/ios/icon-72-2x.png" width="144" />
    <icon gap:platform="webos" src="www/res/icon/webos/icon-64.png" />
    <icon gap:platform="winphone" src="www/res/icon/windows-phone/icon-48.png" />
    <icon gap:platform="winphone" gap:role="background" src="www/res/icon/windows-phone/icon-173-tile.png" />
    <gap:splash gap:platform="android" gap:qualifier="port-ldpi" src="www/res/screen/android/screen-ldpi-portrait.png" />
    <gap:splash gap:platform="android" gap:qualifier="port-mdpi" src="www/res/screen/android/screen-mdpi-portrait.png" />
    <gap:splash gap:platform="android" gap:qualifier="port-hdpi" src="www/res/screen/android/screen-hdpi-portrait.png" />
    <gap:splash gap:platform="android" gap:qualifier="port-xhdpi" src="www/res/screen/android/screen-xhdpi-portrait.png" />
    <gap:splash gap:platform="blackberry" src="www/res/screen/blackberry/screen-225.png" />
    <gap:splash gap:platform="ios" height="480" src="www/res/screen/ios/screen-iphone-portrait.png" width="320" />
    <gap:splash gap:platform="ios" height="960" src="www/res/screen/ios/screen-iphone-portrait-2x.png" width="640" />
    <gap:splash gap:platform="ios" height="1136" src="www/res/screen/ios/screen-iphone-portrait-568h-2x.png" width="640" />
    <gap:splash gap:platform="ios" height="1024" src="www/res/screen/ios/screen-ipad-portrait.png" width="768" />
    <gap:splash gap:platform="ios" height="768" src="www/res/screen/ios/screen-ipad-landscape.png" width="1024" />
    <gap:splash gap:platform="winphone" src="www/res/screen/windows-phone/screen-portrait.jpg" />
    <access origin="http://star-wars-bluff.herokuapp.com" />
</widget>

我在升级到 phonegap ~4.2 时遇到了同样的问题...降级到旧版本解决了这个问题。这似乎是一个 phonegap 错误。

尝试降级到 e。 G。 phonegap@3.5.0-0.20.10

npm install -g phonegap@3.5.0-0.20.10

我解决了我的问题。 当我试图打开 url myserverheroku:3000 时,出现了 404。 我将我的手机连接到 1.1.1.1:3000 这样的 IP 上的 phonegap,所以当我尝试连接到套接字服务器时,phonegap 添加端口 3000。

我的解决方案是替换:

var socket = io.connect('http://star-wars-bluff.herokuapp.com');

var socket = io.connect('http://star-wars-bluff.herokuapp.com:80');

但是现在,socket.io效果不是很好,可能是因为angularjs。 在 destop 中,一切正常,但在移动设备上却不行。

app.js

var swb = angular.module('swb', ['ngRoute', 'swb.controllers']);

swb.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/init', {templateUrl: 'partials/init.html', controller: 'InitCtrl'});
    $routeProvider.when('/welcome', {templateUrl: 'partials/welcome.html', controller: 'WelcomeCtrl'});
    $routeProvider.otherwise({redirectTo: '/init'});
}]);

controllers.js

angular.module('swb.controllers', ['btford.socket-io']).
factory('socket', function (socketFactory) {
  return socketFactory({
    ioSocket: io.connect('http://star-wars-bluff.herokuapp.com:80')
  });
})
.controller('MainCtrl', ['$scope', '$rootScope', '$window', '$location', 'socket', function ($scope, $rootScope, $window, $location, socket) {
    $rootScope.chat = [];
    $rootScope.players = [];
    $rootScope.player = {};
    $rootScope.slide = '';

    $rootScope.back = function() {
      $rootScope.slide = 'slide-right';
      $window.history.back();
    }

    $rootScope.go = function(path){
      $rootScope.slide = 'slide-left';
      $location.url(path);
    }

    socket.on('connected', function (data) {
        $rootScope.players = data.players;
        if(data.player)
            $rootScope.player = angular.copy(data.player);
        $rootScope.chat.push(data.message);
    });
    socket.on('disconnected', function (data) {
        $rootScope.players = data.players;
        $rootScope.chat.push(data.message);
    });
}])
.controller('InitCtrl', ['$scope', '$rootScope', 'socket', function ($scope, $rootScope, socket) {
    $scope.createPlayer = function(){
        socket.emit('adduser', $rootScope.player);
        $rootScope.go('/welcome');
    };
}])
.controller('WelcomeCtrl', ['$scope', '$rootScope', 'socket', function ($scope, $rootScope, socket) {

}]);

index.html:

<!DOCTYPE html>
<html ng-app="swb">
    <head>
        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="msapplication-tap-highlight" content="no" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="css/main.css" />
        <title>Star Wars Bluff</title>
    </head>
    <body ng-controller="MainCtrl">
        <div class="jumbotron text-center">
            <h1>Star Wars Bluff</h1>
        </div>
        <div ng-view ng-class="slide"></div>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular-route.js"></script>
        <script src="http://star-wars-bluff.herokuapp.com/socket.io/socket.io.js"></script>
        <script type="text/javascript" src="js/cordova.js"></script>
        <script type="text/javascript" src="js/app.js"></script>
        <script type="text/javascript" src="js/controllers.js"></script>
        <script type="text/javascript" src="js/socket.js"></script>
    </body>
</html>

init.html

<h2>Bienvenue sur Star Wars Bluff</h2>
<form name="addPlayer" ng-submit="addPlayer.$valid && createPlayer()" novalidate>
    <input placeholder="Votre nom" type="text" ng-model="player.name" required>
    <button type="submit">Jouer</button>
</form>

welcome.js

<h2>Liste des joueurs</h2>
<ul>
    <li ng-repeat="connectedPlayer in players"><span ng-class="{you: player.id==connectedPlayer.id}">{{player.id}} {{connectedPlayer.id}} {{ connectedPlayer.name }}</span></li>
</ul>
<h2>Infos</h2>
<ul>
    <li ng-repeat="info in chat | limitTo: -5">{{ info }}</li>
</ul>

server.js

// init server
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
    res.sendfile('index.html');
});

http.listen(process.env.PORT || 3000);

// usefull functions
var removeByAttr = function(arr, attr, value){
    var i = arr.length;
    while(i--){
       if( arr[i] 
           && arr[i].hasOwnProperty(attr) 
           && (arguments.length > 2 && arr[i][attr] === value ) ){ 

           arr.splice(i,1);

       }
    }
    return arr;
}

// games data & functions
var types = [...];

var cards = [...];

var playersPerRoom = 6,
    players = [],
    rooms = [];

var gameReady = false;

var currentPlayer,
    currentCard,
    currentOpponent,
    currentType;

io.sockets.on('connection', function (socket) {
    socket.on('adduser', function(data){
        socket.player = data;
        if(rooms.length < 1){
            socket.room = 'room1';
            rooms.push(socket.room);
        }else{
            var roomNumber = Math.ceil((players.length + 1) / playersPerRoom);
            socket.room = 'room' + roomNumber;
            if(rooms.indexOf(socket.room) == -1)
                rooms.push(socket.room);
        }
        socket.player.room = socket.room;
        if(players.length < 1)
            socket.player.id = 1;
        else
            socket.player.id = players[players.length - 1].id + 1;
        players.push(socket.player);
        socket.join(socket.room);
        socket.emit('connected', {message: 'Bienvenue sur le serveur ' + socket.room, players: players, player: socket.player});
        socket.broadcast.to(socket.room).emit('connected', {message: socket.player.name + ' est désormais connecté au serveur ' + socket.room, players: players});
    });
    socket.on('disconnect', function(){
        if(socket.player){
            removeByAttr(players, 'id', socket.player.id);
            socket.broadcast.emit('disconnected', {message: socket.player.name + ' a quitté le serveur ' + socket.room, players: players});
            socket.leave(socket.room);
        }
    });
});

当我连接 phone 时,在桌面应用程序中,用户列表和聊天会更新,但在另一个 phone 上它们不会自行更新。

你有什么办法解决我的问题吗?

最后,我使用节点的 utf8 模块对使用 socket.io 发出的字符串进行编码,它工作正常!