swift下GCDAsyncSocket的列子

TcpSocketServer.swift

//
//  TcpSocketServer.swift


import Foundation
import CocoaAsyncSocket

class TcpSocketServer:GCDAsyncSocket {
    
    static let INSTANCE = TcpSocketServer()
    
    typealias serverCallBack = (success:Bool,error:NSError?,data:AnyObject?)->()
    
    let port:UInt16 = 9001
    
    // tcp client array
    var clients = Array<GCDAsyncSocket>()
    
    func startServer()->Bool{
        do{
            self.setDelegate(self,delegateQueue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0))
            try acceptOnPort(self.port)
        }catch{
            printLog("tcp server accept on port error")
            printLog(error)
            return false
        }
        return true
    }

    func receieve(data:String!){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),{()->Void in
            printLog(data)
            TcpSocketServer.INSTANCE.sendAll("this is server "){(success,error,data) in
                
            }
        })
    }

    func sendAll(data:String!,callBack:serverCallBack?){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,{()->Void in
            let result = data.dataUsingEncoding(NSUTF8StringEncoding)
            print("send msg=")
            print(result)
            for client in self.clients{
                client.writeData(result!,withTimeout: -1,tag: 1)
            }
            if callBack == nil{
                return
            }
            dispatch_async(dispatch_get_main_queue(),{()->Void in
                let success:Bool = true
                callBack!(success:success,error:nil,data:nil)
            })
        })
    }
}


extension TcpSocketServer: GCDAsyncSocketDelegate{
    func socket(sock: GCDAsyncSocket,didAcceptNewSocket newSocket: GCDAsyncSocket) {
        //这里sock指服务器的socket,newSocket指客户端的Socket,
        print("[client %s:%d connect server]",newSocket.connectedHost,newSocket.connectedPort)
        //保存客户端的Socket,不然刚连接成功就会自动关闭
        self.clients.append(newSocket)
        //sock只负责连接服务器,newSocket设置成-1,表示一直保持连接
        newSocket.readDataWithTimeout(-1,tag: 100)
    }
    func socket(client: GCDAsyncSocket,didReadData data: NSData,withTag tag: Int)
    {
        print("[recieve client %s:%d message]",client.connectedHost,client.connectedPort)
        var receieveStr:String = (NSString(data:data,encoding: NSUTF8StringEncoding))! as String
        //去除换行符、回车符1
        receieveStr = receieveStr.stringByReplacingOccurrencesOfString("\r",withString: "")
        receieveStr = receieveStr.stringByReplacingOccurrencesOfString("\r",withString: "")
        // 结束删除客户端
        if receieveStr.compare("quit") == NSComparisonResult.OrderedSame {
            client.disconnect()
            let len = self.clients.count
            for i in 0..<len{
                if self.clients[i].connectedUrl == client.connectedUrl{
                    self.clients.removeAtIndex(i)
                }
            }
        }
        self.receieve(receieveStr)
    }
    func socket(client: GCDAsyncSocket,didWriteDataWithTag tag: Int) {
        print("[send client %s:%d message]",client.connectedPort)
        //服务器每次写数据之前都需要读取一次数据,之后才可以返回数据
        client.readDataWithTimeout(-1,tag: 100)
    }
    func socketDidDisconnect(sock: GCDAsyncSocket,withError err: NSError?){
        if ((err) != nil) {
            printLog("断开连接失败")
            return
        }
        print("%s:%d 断开连接",sock.connectedHost,sock.connectedPort)
        
    }
}

TcpSocketClient.swift
//
//  TcpSocketClient.swift

import Foundation

class TcpSocketClient:GCDAsyncSocket {
    
    static let INSTANCE = TcpSocketClient()
    
    typealias clientCallBack = (success:Bool,data:AnyObject?)->()
    
    func receieve(data:String!){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,{()->Void in
            print(data)
            let t = "this is client"
            TcpSocketClient.INSTANCE.send(t){(success,data) in
            }
        })
    }
    
    func send(data:String!,callBack:clientCallBack?){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,{()->Void in
            let result = data.dataUsingEncoding(NSUTF8StringEncoding)
            self.writeData(result!,tag: 1)
            if callBack == nil{
                return
            }
            dispatch_async(dispatch_get_main_queue(),data:nil)
            })
        })
    }
    
    func connect(host:String,port:UInt16)->Bool{
        self.setDelegate(self,0))
        do{
            try self.connectToHost(host,onPort: port)
        }catch {
            print("connect %s:%d fail ",host,port)
            print(error)
            return false
        }
        return true
    }
}


extension TcpSocketClient: GCDAsyncSocketDelegate{
    
    func socket(client: GCDAsyncSocket,withTag tag: Int)
    {
        print("[recieve server %s:%d message]",encoding: NSUTF8StringEncoding))! as String
        //去除换行符、回车符
        receieveStr = receieveStr.stringByReplacingOccurrencesOfString("\r",withString: "")
        // 结束删除客户端
        if receieveStr.compare("quit") == NSComparisonResult.OrderedSame {
            client.disconnect()
        }
        self.receieve(receieveStr)
    }
    func socket(client: GCDAsyncSocket,didWriteDataWithTag tag: Int) {
        print("[send server %s:%d message]",tag: 100)
    }
    func socket(sock: GCDAsyncSocket,didConnectToHost host: String,port: UInt16) {
        print("[connect server %s:%d success]",sock.connectedPort)
    }
    func socketDidDisconnect(sock: GCDAsyncSocket,withError err: NSError?){
        if ((err) != nil) {
            print("%s:%d 断开连接失败",sock.connectedPort)
            return
        }
        print("%s:%d 断开连接",sock.connectedPort)
        
    }
}

调用方式:

server端:

TcpSocketServer.INSTANCE.startServer()

client端:

TcpSocketClient.INSTANCE.connect("192.168.0.1",port:9001)

相关文章

Swift 正式开源!Swift 团队很高兴宣布 Swift 开始开源新篇章。自从苹果发布 Swfit 编程语言,就成为了...
快,快,快!动动您的小手,分享给更多朋友! 苹果去年推出了全新的编程语言Swift,试图让iOS开发更简单...
开发者(KaiFaX) 面向开发者、程序员的专业平台! 和今年年初承诺的一样,苹果贴出了Swift语言的源码,...
本文由@Chun发表于Chun Tips :http://chun.tips/blog/2014/12/11/shi-yong-swift-gou-jian-zi-ding-yi...
本文由CocoaChina译者leon(社区ID)翻译 原文:THE RIGHT WAY TO WRITE A SINGLETON 在之前的帖子里聊过...
本文由CocoaChina译者leon(社区ID)翻译 原文:THE RIGHT WAY TO WRITE A SINGLETON 在之前的帖子里聊过...