在 Swift 中创建一个套接字 [英] Create a socket in Swift
问题描述
我正在尝试快速编写一个简单的回显服务器.我发现的示例是 非功能性和低级 或 用objective-c编写.
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.
我在很多事情上都失败了,我将从头开始.我无法使用 CFSocketCreate
等更高级别的函数创建一个简单的套接字.这就是我最终的结果:
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
}
}
我是 xcode/objectivec/swift 的新手,我什至很难理解错误消息.上面的代码让我很简单
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) -> ()' 不能转换为 '@lvalue inout $T10'
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.
推荐答案
如果有人还在寻找这个问题的答案.我稍微修改了代码.回调中有一些输入问题,而且它不能是类上的函数.
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)
}
}
这篇关于在 Swift 中创建一个套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!