투케이2K

494. (ios/swift5) [CocoaAsyncSocket] 기본 TCP IP 소켓 통신 클래스 구현 - connect , write , read , close 본문

IOS

494. (ios/swift5) [CocoaAsyncSocket] 기본 TCP IP 소켓 통신 클래스 구현 - connect , write , read , close

투케이2K 2024. 4. 17. 19:59
반응형

[개발 환경 설정]

개발 툴 : XCODE

개발 언어 : SWIFT5

 

[소스 코드]

 

import UIKit
import CocoaAsyncSocket


class CocoaAsyncSocketController: UIViewController, GCDAsyncSocketDelegate { // [GCDAsyncSocketDelegate 추가]
    


    // -----------------------------------------------------------------------------------------
    // MARK: - [전역 변수 선언 실시]
    // -----------------------------------------------------------------------------------------
    let host:String = "192.168.0.25"
    let port:Int16 = 5001
    
    var asyncSocket: GCDAsyncSocket! = nil
    

    
    

    // -----------------------------------------------------------------------------------------
    // MARK: - [뷰 로드 실시]
    // -----------------------------------------------------------------------------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        S_Log._F_(description: "뷰 로드 실시", data: nil)
        
        // [뷰 컨트롤러 배경 색상 지정]
        self.view.backgroundColor = UIColor.init(rgb: 0xffffff).withAlphaComponent(1.0)
        
        // [asyncSocket 객체 초기화]
        self.asyncSocket = nil        
    }
    




    // -----------------------------------------------------------------------------------------
    // MARK: - [User] : [소켓 연결시작 메소드]
    // -----------------------------------------------------------------------------------------
    func connect()
    {
        let serverIp = self.host
        let portNumber:UInt16 = UInt16(self.port)
        
        if self.asyncSocket == nil
        {
            self.asyncSocket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
        }
        

        // [소켓 연결 상태 체크]
        if !self.asyncSocket.isConnected {
            do {
                try self.asyncSocket.connect(toHost: serverIp, onPort: portNumber, withTimeout: 10)
            }
            catch
            {
                S_Log._D_(description: S_FinalMsg.LOG_BUG_STATE, data: [
                    "catch :: \(error.localizedDescription)"
                ])
            }
        }
        else
        {
            S_Log._D_(description: "connect :: 이미 소켓에 연결 된 상태입니다", data: nil)
        }
    }
    




    // -----------------------------------------------------------------------------------------
    // MARK: - [User] : [소켓 연결 종료 메소드]
    // -----------------------------------------------------------------------------------------
    func disconnect() {

        // [객체 널 체크]
        if self.asyncSocket != nil
        {
            self.asyncSocket.disconnect()
        }
    }
    




    // -----------------------------------------------------------------------------------------
    // MARK: - [User] : [소켓 데이터 쓰기]
    // -----------------------------------------------------------------------------------------
    func sendCommand_100() {

        // [객체 널 체크]
        if self.asyncSocket != nil
        {
            var byteData:[UInt8] = [UInt8]()
            
            byteData.append(49) // 1
            byteData.append(48) // 0
            byteData.append(48) // 0
            
            let cmdData = Data(bytes: byteData, count: 3) // [버퍼 길이 지정]
            
            self.asyncSocket.write(cmdData, withTimeout: -1, tag: 100) // [데이터 쓰기]
        }
    }
    
    
    
    


    // -----------------------------------------------------------------------------------------
    // MARK: - [GCDAsyncSocketDelegate] : [소켓 연결 완료]
    // -----------------------------------------------------------------------------------------
    public func socket(_ socket: GCDAsyncSocket, didConnectToHost host: String, port p:UInt16){
        S_Log._D_(description: "GCDAsyncSocket :: didConnectToHost :: 소켓 연결 완료", data: nil)        

        // [데이터 쓰기]
        self.sendCommand_100()
    }
    




    // -----------------------------------------------------------------------------------------
    // MARK: - [GCDAsyncSocketDelegate] : [소켓 데이터 쓰기 완료]
    // -----------------------------------------------------------------------------------------
    public func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) {
        S_Log._D_(description: "GCDAsyncSocket :: didWriteDataWithTag :: 소켓 데이터 쓰기 완료", data: ["TAG :: \(tag)"])
        

        // [tag] : 100
        if tag == 100
        {
            S_Log._D_(description: "GCDAsyncSocket :: didWriteDataWithTag :: Socket Write Data [100] >> Socket Read Data [200]", data: nil)

            // [데이터 읽기]
            sock.readData(withTimeout: -1, tag: 200)            
        }

    }
    





    // -----------------------------------------------------------------------------------------
    // MARK: - [GCDAsyncSocketDelegate] : [didReceive] : [소켓 응답 수신]
    // -----------------------------------------------------------------------------------------
    public func socket(_ sock: GCDAsyncSocket, didReceive trust: SecTrust, completionHandler: @escaping (Bool) -> Void) {
        S_Log._D_(description: "GCDAsyncSocket :: didReceive :: 소켓 응답 수신 확인", data: nil)
    }
    





    // -----------------------------------------------------------------------------------------
    // MARK: - [GCDAsyncSocketDelegate] : [didRead] : [소켓 데이터 읽기 완료]
    // -----------------------------------------------------------------------------------------
    public func socket(_ sock: GCDAsyncSocket, didRead: Data, withTag tag:CLong){
        S_Log._D_(description: "GCDAsyncSocket :: didRead :: 소켓 데이터 읽기 완료", data: ["TAG :: \(tag)", "SIZE :: \(didRead.count)", "HEX :: \(didRead.toHexString())"])

        // [데이터 사이즈]
        var readSize = didRead.count
        

        // [tag] : 200
        if tag == 200 {
            let recvData = didRead.bytes // [바이트 읽기]
            
            // [추가 로직 처리]
            
        }
        
    }    





    // -----------------------------------------------------------------------------------------
    // MARK: - [GCDAsyncSocketDelegate] : [DidDisconnect] : [소켓 연결 종료 완료]
    // -----------------------------------------------------------------------------------------
    public func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
        S_Log._D_(description: "GCDAsyncSocket :: DidDisconnect :: 소켓 연결 종료 완료", data: nil)
        

        // [객체 초기화]
        self.asyncSocket = nil
        
    }


} // [클래스 종료]

 

반응형
Comments