问题
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:
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.
回答1:
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)
}
}
回答2:
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
来源:https://stackoverflow.com/questions/26430251/create-a-socket-in-swift