Create a socket in Swift

I’m trying to write a simple echo server with swift. The examples I found are either non-functional and low-level or written in objective-c.

I failed at a lot of things, I will start from the top. I cannot manage to create a simple socket using higher-level functions like CFSocketCreate. This is what I ended up with:

  • How to implement real-time communication between iOS app and server in Swift?
  • Using sockets in Swift like in Java
  • Send multiple OBD commands together and get response simultaneously
  • How to handle socket connection's events when app is in background?
  • Sockets with Swift
  • SSL Socket connection iOS
  • class EchoServer : NSObject, NSStreamDelegate
    {
        private var serverSocket: CFSocketRef?
    
        func start()
        {
            self.serverSocket = CFSocketCreate(kCFAllocatorDefault, AF_INET, SOCK_STREAM, 0, 2, &self.acceptConnection, NSNull())
        }
    
        func acceptConnection(socket: CFSocketRef, type: CFSocketCallBackType, address: CFDataRef, data: UnsafePointer<Void>, info: UnsafeMutablePointer<Void>)
        {
            // Accept connection and stuff later
        }
    }
    

    I am new to xcode/objectivec/swift and I’m having a hard time even understanding the error message. The above code leaves me simply with

    EchoServer.swift:31:93: ‘(CFSocketRef, type: CFSocketCallBackType, address: CFDataRef, data: UnsafePointer, info: UnsafeMutablePointer) -> ()’ is not convertible to ‘@lvalue inout $T10’

    I’m not even able to make head or tail of this.

    2 Solutions Collect From Internet About “Create a socket in Swift”

    If somebody is still looking for the answer on this question. I modified code a little. There were some typing issues in the callback, plus it could not be a function on the class.

    import CoreFoundation
    
    func acceptConnection(socket: CFSocket!, type: CFSocketCallBackType, address: CFData!, data: UnsafePointer<Void>, info: UnsafeMutablePointer<Void>)
    {
        // Accept connection and stuff later
    }
    
    class EchoServer : NSObject, NSStreamDelegate
    {
        private var serverSocket: CFSocketRef?
    
        func start()
        {
            self.serverSocket = CFSocketCreate(kCFAllocatorDefault, AF_INET, SOCK_STREAM, 0, 2, acceptConnection, nil)
        }
    }
    

    You might take a look at GCDAsyncSocket as it handles a lot of the “plumbing” for you.

    I was building a simple server in Swift as a learning exercise. There might be some things in there you could use. Here is the class that deals with creating the socket:
    Github Link