[Swift 3] TCPIP Socket 통신 클래스 소스 코드 및 사용법

by digipine posted Nov 02, 2017
?

Shortcut

PrevPrev Article

NextNext Article

ESCClose

Larger Font Smaller Font Up Down Go comment Print

Swift3으로 TCPIP Socket  구현하려면 막막한데요. Stream Class 이용하면 간단히 구현   있습니다.

아래와 같이 Deleate 등록하면 에러 이벤트 처리도 가능합니다.

 

import Foundation

 

class TcpSocket: NSObjectStreamDelegate {

    

    

    var host:String?

    var port:Int?

    var inputStream: InputStream?

    var outputStream: OutputStream?

    

    func connect(host: String, port: Int) {

        

        self.host = host

        self.port = port

        

        Stream.getStreamsToHost(withName:host, port : port, inputStream: &inputStream, outputStream: &outputStream)

        

        if inputStream != nil && outputStream != nil {

            

            // Set delegate

            inputStream!.delegate = self

            outputStream!.delegate = self

            

            // Schedule

            inputStream!.schedule(in: .main, forMode: RunLoopMode.defaultRunLoopMode)

            outputStream!.schedule(in: .main, forMode: RunLoopMode.defaultRunLoopMode)

            

            print("Start open()")

            

            // Open!

            inputStream!.open()

            outputStream!.open()

        }

    }

    

    func send(data: Data) -> Int {

        let bytesWritten = data.withUnsafeBytes { outputStream?.write($0, maxLength: data.count) }

        return bytesWritten!

    }

    

    //    func send(data: String) -> Int {

    //        let bytesWritten = outputStream?.write(data, maxLength:data.characters.count)

    //        return bytesWritten!

    //    }

    

    func recv(buffersize: Int) -> Data {

        var buffer = [UInt8](repeating :0, count : buffersize)

        

        let bytesRead = inputStream?.read(&buffer, maxLength: buffersize)

        var dropCount = buffersize - bytesRead!

        if dropCount < 0 {

            dropCount = 0

        }

        let chunk = buffer.dropLast(dropCount)

        return Data(chunk)

    }

    

    func disconnect() {

        inputStream?.close()

        outputStream?.close()

    }

    

    func stream(_ stream: Stream, handle eventCode: Stream.Event) {

        

        print("event:\(eventCode)")

        

        if stream === inputStream {

            switch eventCode {

            case Stream.Event.errorOccurred:

                print("inputStream:ErrorOccurred")

            case Stream.Event.openCompleted:

                print("inputStream:OpenCompleted")

            case Stream.Event.hasBytesAvailable:

                print("inputStream:HasBytesAvailable")

                

                

            default:

                break

            }

        }

        else if stream === outputStream {

            switch eventCode {

            case Stream.Event.errorOccurred:

                print("outputStream:ErrorOccurred")

            case Stream.Event.openCompleted:

                print("outputStream:OpenCompleted")

            case Stream.Event.hasSpaceAvailable:

                print("outputStream:HasSpaceAvailable")

                

                

            default:

                break

            }

        }

    }

    

}

 

 

 

사용법

 

 let socket = TcpSocket()

 

 ....

 

 

 socket.connect(host: "118.34.167.155", port: 5552)

 

 

 let query = "HELLO SWIFT SOCKET!"

 let dataQuery = query.data(using: String.Encoding.utf8, allowLossyConversion: true)

 let sentCount = socket.send(data: dataQuery!)

 //let sentCount = socket.send(data: query)

 print("sentCount : \(sentCount)")

 

 let buffersize = 1024

 let chunk = socket.recv(buffersize: buffersize)

 

 var getString : String?

 

 if(chunk.count > 0){

 getString = String(bytes: chunk, encoding: String.Encoding.utf8)!

 print("received : \(getString!)")

 }

 

 

 connect.disconnect()

 
TAG •

Articles

1 2 3