Swift iOS application does not connect to Server u

2019-07-11 16:48发布

问题:

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');
});

回答1:

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



回答2:

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



回答3:

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()
        }
    }