Pavan Ravipati
Pavan Ravipati

Reputation: 1870

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.

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 defined in client

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

Upvotes: 0

Views: 1160

Answers (1)

Pavan Ravipati
Pavan Ravipati

Reputation: 1870

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;

})

Upvotes: 0

Related Questions