使用CFStreamCreatePairWithSocketToHost的TCP套接字连接不起作用

时间:2015-08-09 02:01:48

标签: ios sockets tcp io

我是swift Programming的新手。我正在尝试从我的ios应用程序连接到服务器套接字。我有一个View控制器,在按钮操作中我调用函数连接到套接字服务器

class Connection : NSObject, NSStreamDelegate {
        let serverAddress: CFString = "192.168.1.104"
        let serverPort: UInt32 = 5012

        private var inputStream: NSInputStream!
        private var outputStream: NSOutputStream!

        func connect() {
            println("connecting...")

            var readStream:  Unmanaged<CFReadStream>?
            var writeStream: Unmanaged<CFWriteStream>?

            CFStreamCreatePairWithSocketToHost(nil, self.serverAddress, self.serverPort, &readStream, &writeStream)

            self.inputStream = readStream!.takeRetainedValue()
            self.outputStream = writeStream!.takeRetainedValue()

            self.inputStream.delegate = self
            self.outputStream.delegate = self

            self.inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
            self.outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)

            self.inputStream.open()
            self.outputStream.open()
        }

        func stream(stream: NSStream, handleEvent eventCode: NSStreamEvent) {
            println("stream event")
        }
    }

我已在Connection类中将委托设置为self,但在连接到服务器套接字后,我的流函数未被触发。

pygame.display.set_mode(dimensions, pygame.RESIZEABLE|pygame.DOUBLEBUF)

任何人都可以帮我解决为什么在连接上调用流函数的原因?

2 个答案:

答案 0 :(得分:1)

我正在使用NSStream类的 getStreamsToHostWithName 函数。它比 CFStreamCreatePairWithSocketToHost

更容易和更容易
 func initNetworkCommunication() {

    print("connecting...")

    let serverAddress = "gzoa.vps.infomaniak.com"
    let serverPort = 1234

    NSStream.getStreamsToHostWithName(serverAddress, port: serverPort, inputStream: &inputStream, outputStream: &outputStream)

    self.inputStream!.delegate = self
    self.outputStream!.delegate = self

    self.inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
    self.outputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)

    self.inputStream!.open()
    self.outputStream!.open()
}

答案 1 :(得分:0)

您可以使用此

import Foundation

typealias OnComing = (String!) -> (Void)

class SocketClient: NSObject, StreamDelegate {

    var host:String?
    var port:Int?
    var inputStream: InputStream?
    var outputStream: OutputStream?

    var status = false;
    var output = ""
    var bufferSize = 1024;

    var onComing:OnComing!

    func makeCFStreamConnection(host: String, port: Int, onComing:@escaping OnComing) {

        self.host = host
        self.port = port
        self.onComing = onComing

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

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

            self.inputStream!.delegate = self
            self.outputStream!.delegate = self

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

            self.inputStream!.open()
            self.outputStream!.open()

        }


    }

    func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
        if aStream === self.inputStream {
            switch eventCode {
            case Stream.Event.errorOccurred:
                break
            case Stream.Event.openCompleted:
                break
            case Stream.Event.hasBytesAvailable:
                read()
                break
            default:
                break
            }
        } else if aStream === self.outputStream {
            switch eventCode {
            case Stream.Event.errorOccurred:
                break
            case Stream.Event.openCompleted:
                break
            case Stream.Event.hasSpaceAvailable:
                break
            default:
                break
            }
        }
    }

    func read() {
        output = ""
        var buffer = [UInt8](repeating: 0, count: bufferSize)
        while (self.inputStream!.hasBytesAvailable) {
            let bytesRead: Int = inputStream!.read(&buffer, maxLength: buffer.count)
            if bytesRead >= 0 {
                output += NSString(bytes: UnsafePointer(buffer), length: bytesRead, encoding: String.Encoding.ascii.rawValue)! as String
            } else {
                print("# Stream read() error")
            }
        }
        self.onComing(output)
    }

    func write(message:String) {
        let encodedDataArray = [UInt8]("\(message)\n".utf8)
        self.outputStream?.write(encodedDataArray, maxLength: encodedDataArray.count)
    }
}