简体   繁体   中英

Socket.emit doesn't work with Ionic

I am trying to create a socket connection between my ionic application and a socket server that I've built.

  • The socket connection won't work when running the app in iOS simulator using ionic run ios --target="iPhone-6-Plus"

  • The socket connection works when serving the app in the browser using ionic serve .

My Code

I have a socket service in my app client that connects to my socket server:

.factory('Sockets', function($http, socketFactory){

  var myIoSocket = io.connect('localhost:5000');

  var mySocket = socketFactory({
    ioSocket: myIoSocket
  });

  return mySocket;

})

Here is what my client socket request looks like:

angular.module('crewapp.chat', [])
.controller('ChatController', function($scope, Auth, Sockets, $localStorage){
  $scope.test = 'Chats';
  Sockets.emit('join room', $localStorage.groupname)

});

Here is what my socket server (in short) looks like

io.sockets.on('connection', function(socket) {
  socket.on('join room', function(room) {
    socket.room = room;
    socket.join(room);
    console.log(room);
});

What I've Tried

  1. I've tried seeing if Socket.emit is defined in the app which it is:

客户端中定义的Socket.emit

  1. I've generalized where the socket server should log by placing a console.log in socket.on('connection') callback's function body.

I figured out what the issue was. When connecting to the socket server in ionic / cordova you must prepend the server url with http:// . The reason the application will still work in the browser is because the browser will automatically add the prefix.

.factory('Sockets', function($http, socketFactory){

  var myIoSocket = io.connect('http://localhost:5000');

  var mySocket = socketFactory({
    ioSocket: myIoSocket
  });

  return mySocket;

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM