Lanatbaryazid
Lanatbaryazid

Reputation: 63

Swift iOS application does not connect to Server using Socket.IO

I'm about to write a very simple iOS application. I want the application to connect to a server by using Socket.IO. I've already installed Socket.IO with Cocoapods for my project and everything went well. The problem is after I run my server and then the application simulator, the application doesn't get connected to the server. I don't get any kind of error message or something like that but the server should print a message on the console/terminal when a socket is being connected.

This is the socket manager class

import UIKit
import SocketIO

class SocketManager: NSObject {

    static let sharedInstance = SocketManager()

    override init() {
        super.init()
    }

    var socket: SocketIOClient = SocketIOClient(socketURL:         NSURL(string: "localhost:3000")!)

    func establishConnection() {
        socket.connect()
    }

    func closeConnection() {
        socket.disconnect()
    }
}

This is the AppDelegeate class:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        SocketManager.sharedInstance.closeConnection()
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        SocketManager.sharedInstance.establishConnection()
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
}

And finally my server code written in node.js

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

app.get('/', function(req, res){
  res.send('<h1>Server Chat</h1>');
});

http.listen(3000, function(){
  console.log('Listening on *:3000');
});

io.on('connection', function(clientSocket){
  console.log('a user connected');
});

Upvotes: 4

Views: 9069

Answers (5)

Serigne Mor Ba
Serigne Mor Ba

Reputation: 11

I used version 16.0.1 socket-io-client-Swift with this piece of code below and it worked

import SocketIO

 var manager:SocketManager?

func connected(status: String) {
    manager = SocketManager(socketURL: NSURL(string: "http://15.236.177.78:3000")! as URL, config: [
      .log(true),
      .compress,
      .reconnects(true),
      .reconnectWait(1),
      .forceWebsockets(true)
  ])
    print("socket try to connecting.....")

let socket = manager?.defaultSocket

socket?.on(clientEvent: .connect) {data, ack in
    print("socket connected")
    socket?.emit("newPrestation", ["id": "63ab374015f016deb34e7899", "status": status, "prestataireId": DataManagerPreference.getUserId() ?? ""])
}
socket?.on(clientEvent: .error) {data, ack in
    print("socket error")
}
socket?.on("onMessage"){data, ack in
    print("socket newPrestation \(data)")
}


socket?.connect()
}

Upvotes: 1

Duc Trung Mai
Duc Trung Mai

Reputation: 2608

// Case 1: This won't work
class Myclass{
  func initSocket() {
    let manager = SocketManager(socketURL: URL(string: BASE_URL)!, config: [.log(true), .compress])
    socket = manager.defaultSocket
    socket.on(clientEvent: .connect) {data, ack in
      print("SOCKET CONNECTED")
    }
  }
}

// Case 2: This works
class Myclass {
  let manager = SocketManager(socketURL: URL(string: BASE_URL)!, config: [.log(true), .compress])
  var socket: SocketIOClient!
  func initSocket() {
    socket = manager.defaultSocket

    socket.on(clientEvent: .connect) {data, ack in
      print("SOCKET CONNECTED")
    }
  }
}
  • In case 1: server see a client connected, but on iOS side, .connect event never fires, and after awhile on server disconnect event is fired

Upvotes: 0

Manni84
Manni84

Reputation: 11

This is what works for me:

dict = [.connectParams(["payloadId": getPayloadId(), "version": getVersion()])]

socket = SocketIOClient(socketURL: URL(string: "http://localhost:8080")!, config: dict)
socket.connect()

socket.on("connect") {data, ack in
        if(self.socket.status == .connected) {
            print("socket connected")
        }
        else {
            self.reconnectSocket()
        }
    }

Upvotes: 0

Vishakha Panchal
Vishakha Panchal

Reputation: 1

try to write SocketIOClient(socketURL: URL(string: "http://192.168.0.8:3000")!) instead of SocketIOClient(socketURL: NSURL(string: "localhost:3000")!) and write "your server ip address"

i hope its work for you

Upvotes: 0

M.Sabaa
M.Sabaa

Reputation: 319

I would try to use actual IP instead of "Localhost" , i think it is connecting to its self as a device and that is why is not making an error

maybe you should mention if you are trying using a simulator or actual device also check for firewall

Upvotes: 3

Related Questions