【问题标题】:Connect a client app Android to a server written with Sails.js using socket.io使用 socket.io 将客户端应用程序 Android 连接到用 Sails.js 编写的服务器
【发布时间】:2015-07-02 14:07:25
【问题描述】:

这是我的情况:我有一个用sails.js 编写的服务器,我有一个用户模型。我有一个仪表板,我可以在其中查看所有用户,创建新用户,删除它们等等......现在我想创建一个 android 应用程序,我可以使用 socket.io 在其中获取有关用户发生事件的通知模型。 示例:如果我从仪表板中删除用户,我希望应用程序从服务器接收到用户已被删除的通知。

这是我的应用代码:

公共类 MainActivity 扩展 Activity {

//socket instance
private Socket mSocket;
{
    try {
        mSocket = IO.socket("http://server_url:port/user");
    } catch (URISyntaxException e) {
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); //set the layout for this activity

    final TextView tv = (TextView) findViewById(R.id.textView);

    mSocket.on("user", new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            tv.setVisibility(View.INVISIBLE);
        }
    });

    mSocket.connect();

    final Button btn_createUser = (Button)findViewById(R.id.button);
    btn_createUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mSocket.connected()) {
                //tv.setVisibility(View.INVISIBLE);
            }
        }
    });
}

}

就像我使用仪表板将套接字连接到服务器一样,我在这里做了同样的事情,但似乎套接字没有连接,事实上,当我从仪表板中删除用户时,我没有收到任何通知。

这是我在仪表板中使用的代码(有效),用于将我的套接字连接到服务器并监听来自用户模型的更新:

//connect to the server and listen to updates from user model
      io.socket.get('/user', function(data, jwres) {
          $scope.users = data;
          $scope.$apply(); //write users in the table...
      });
      //wait for updates...
io.socket.on('user', function serverResponded (data) {
          if(data.verb == "updated")
          {
              //get the user index in the array and update it
              var index = getIndex(data.id, $scope.users);
              $scope.users[index].online = data.data.online;
              $scope.$apply();
          }
          if(data.verb == "destroyed")
          {
              //get the user index in the array and remove it
              var index = getIndex(data.id, $scope.users);
              $scope.users.splice(index, 1);
              $scope.$apply();
          }
          if(data.verb == "created")
          {
              //simply update the array
              $scope.users.push(data.data);
              $scope.$apply();
          }
      });

现在,我认为我在 android 应用程序中遗漏的只是 GET 请求,它会自动将我的套接字订阅到模型并在发生某些事情时得到通知……但我不知道该怎么做。

我希望我已经足够清楚了...感谢所有回答我的人!

PS:我不想使用AndroidAsync,因为我需要socket.io的终极版本!

【问题讨论】:

    标签: android angularjs sockets socket.io sails.js


    【解决方案1】:

    如果有人需要,我找到了解决方案:https://github.com/balderdashy/sails/issues/2640 在这里您可以找到解决问题的方法! :)

    【讨论】:

      猜你喜欢
      • 2012-04-14
      • 2018-05-12
      • 1970-01-01
      • 2012-12-05
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多