Swift中的TCP套接字

时间:2014-09-07 16:25:31

标签: sockets tcp swift gcdasyncsocket

我正在尝试使用GCDAsyncSocket在swift中编写TCP套接字客户端,但是我遇到了很多问题。在我的代码中,我有一个NSTextField(称为框),这是我的代码:     导入Cocoa

class AppDelegate: NSObject, NSApplicationDelegate 
{

    @IBOutlet weak var window: NSWindow!
    @IBOutlet weak var box: NSTextField!

    let bsocket = GCDAsyncSocket(delegate: AppDelegate.self, delegateQueue: dispatch_get_main_queue())

    func applicationDidFinishLaunching(aNotification: NSNotification?)
    {
        var port:UInt16 = 8090
        if (!bsocket.connectToHost("localhost", onPort: port, error: nil))
        {
            println("Error")
        }
        else
        {
            println("Connecting...")
        }
        var request:String = "Arn.Preg:3302:"
        var data:NSData = request.dataUsingEncoding(NSUTF8StringEncoding)!
        bsocket.writeData(data, withTimeout: -1.0, tag: 0)
        bsocket.readDataWithTimeout(-1.0, tag: 0)
    }

    func applicationWillTerminate(aNotification: NSNotification?) 
    {
        // Insert code here to tear down your application
    }

    func socket(socket : GCDAsyncSocket, didReadData data:NSData, withTag tag:UInt16)
    {
        var response = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("Received Response")
        box.stringValue = box.stringValue + "\n" + response
    }

    func socket(socket : GCDAsyncSocket, didConnectToHost host:String, port p:UInt16)
    {
        println("Connected to \(host) on port \(p).")
        box.stringValue = box.stringValue + "\n" + "Connected to \(host) on port \(p)."
    }
}

当我运行代码时,我想要它做的是显示TCP服务器在文本框中返回的文本,但由于某种原因,函数

func socket(socket : GCDAsyncSocket, didReadData data:NSData, withTag tag:UInt16)

永远不要跑。当我在终端中使用telnet命令来实现相同的结果时,服务器返回:

Marzuk:~ marzukrashid$ telnet localhost 8090
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Arn.TipoSer:XPL0:

然后,当我输入" Arn.Preg:3302:"时,服务器返回:

Marzuk:~ marzukrashid$ telnet localhost 8090
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Arn.TipoSer:XPL0:
Arn.Preg:3302:
Arn.Resp:3302=329351:

当我输入" Arn.Preg:3302:"服务器返回" Arn.Resp:3302 = 329351:",这是我想要实现的结果,我希望我的应用程序中的NSTextField显示" Arn.Resp:3302 = 329351 :"

我的问题是为什么我的代码没有这样做,以及如何修复我的代码。

感谢。

编辑:当我运行程序时,NSTextField为空,程序打印"正在连接......"但它没有打印"已连接"或其他任何东西。

1 个答案:

答案 0 :(得分:2)

套接字初始值设定项中的self并不是您的想法 - 它实际上是对您的AppDelegate类型的引用。尝试在applicationDidFinishLaunching()内部进行初始化。

class AppDelegate: NSObject, NSApplicationDelegate 
{

    @IBOutlet weak var window: NSWindow!
    @IBOutlet weak var box: NSTextField!
    var bsocket: GCDAsyncSocket!

    func applicationDidFinishLaunching(aNotification: NSNotification?)
    {
        bsocket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
        // ...