流套接字等待服务器Swift

时间:2017-09-23 04:50:24

标签: swift sockets server stream serversocket

我创建一个脚本以接收服务器命令。我的目标是从服务器1接收消息......等待等等。然后从服务器2接收消息然后执行动作。这实际上使用DispatchQueue和DispatchGroup。如果服务器在此应用程序启动之前运行,我的代码就可以运行。

import UIKit
import Dispatch

let addr = "192.168.0.100"
let addr2 = "192.168.0.104"
let port = 12345  //PORT Num
var buffer = [UInt8](repeating: 0, count: 255)
var buffer2 = [UInt8](repeating: 0, count: 255)

var inpVive1 : InputStream?
var outVive1 : OutputStream?

var inpVive2 : InputStream?
var outVive2 : OutputStream?

let secondsDelay = 0

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let queue:DispatchQueue = DispatchQueue.global(qos: .userInitiated)
        let group:DispatchGroup = DispatchGroup()

        group.enter()
        queue.async {
            self.Connection1()
            group.leave()
        }

        group.enter()
        queue.async {
            self.Connection2()
            group.leave()
        }


        group.notify(queue: queue, execute: {// do something when all tasks in queue complete})
            print("Everything is received!!!!!!!!!!!!")
        })
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func Connection1() {
        print("Listening vive1")
        Stream.getStreamsToHost(withName: addr, port: port, inputStream: &inpVive1, outputStream: &outVive1)

        if inpVive1 != nil && outVive1 != nil {

            let inputStreamVive1 : InputStream = inpVive1!
            let outputStreamVive1 : OutputStream = outVive1!

            inputStreamVive1.delegate = self as? StreamDelegate
            outputStreamVive1.delegate = self as? StreamDelegate

            inputStreamVive1.schedule(in: .main, forMode: .defaultRunLoopMode)
            outputStreamVive1.schedule(in: .main, forMode: .defaultRunLoopMode)

            inputStreamVive1.open()
            outputStreamVive1.open()
            print("Tunnel vive1 ouvert")

            if outputStreamVive1.streamError == nil && inputStreamVive1.streamError == nil {

                while true {
                    let readCharsVive1: Int = inputStreamVive1.read(&buffer, maxLength: buffer.count)
                    if (readCharsVive1 > 0) {
                        let readStringVive1: String = NSString(data: NSData(bytes:buffer, length:readCharsVive1) as Data, encoding: String.Encoding.utf8.rawValue)! as String
                        print("Message received vive1 :", readStringVive1) //  data from server
                        usleep(300 * 1000) // wait 300 msec (just wait. it is no meaning. using as "NOP")
                        inputStreamVive1.close()
                        outputStreamVive1.close()

                    }
                    else {
                        print ("server1 closed connection")
                        inputStreamVive1.close()
                        outputStreamVive1.close()
                        break
                    }

                }

            }
        }

    }

    func Connection2() {
        print("Listening vive2")
        Stream.getStreamsToHost(withName: addr2, port: port, inputStream: &inpVive2, outputStream: &outVive2)

        if inpVive2 != nil && outVive2 != nil {
            let inputStreamVive2 : InputStream = inpVive2!
            let outputStreamVive2 : OutputStream = outVive2!
            inputStreamVive2.open()
            outputStreamVive2.open()
            print("Tunnel vive2 ouvert")

            if outputStreamVive2.streamError == nil && inputStreamVive2.streamError == nil {
                while true {
                    let readCharsVive2: Int = inputStreamVive2.read(&buffer2, maxLength: buffer2.count)
                    if (readCharsVive2 > 0) {
                        let readStringVive2: String = NSString(data: NSData(bytes:buffer2, length:readCharsVive2) as Data, encoding: String.Encoding.utf8.rawValue)! as String
                        print("Message received vive2 :", readStringVive2) //  data from server
                        usleep(300 * 1000) // wait 300 msec (just wait. it is no meaning. using as "NOP")
                        inputStreamVive2.close()
                        outputStreamVive2.close()

                    }
                    else {
                        print ("server2 closed connection")
                        inputStreamVive2.close()
                        outputStreamVive2.close()
                        break
                    }

                }
            }


        }
    }



}

当这台服务器已经运行时,我成功连接了服务器。现在我希望能够等到它没有运行的情况下开始。有什么想法吗?

1 个答案:

答案 0 :(得分:-1)

实际上这解决了我的问题:

import UIKit

let addr = "127.0.0.1"
let port = 12345  //PORT Num

var buffer = [UInt8](repeating: 110, count: 4096)

var inputStream : InputStream?
var outputStream : OutputStream?
var animationTimer: Timer!

let readChars: Int = inputStream!.read(&buffer, maxLength: buffer.count)

class ViewController: UIViewController, StreamDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()


        Connection()
    }

    func Connection() {

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

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

                print("connecting")

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

                inputStream?.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
                outputStream?.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)

                print("Start open()")

                inputStream?.open()
                outputStream?.open()
        }
    }

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

        if aStream === inputStream {
            switch eventCode {
            case Stream.Event.errorOccurred:
                print("input: ErrorOccurred: \(String(describing: aStream.streamError?.localizedDescription))")
                Connection()
                break
            case Stream.Event.openCompleted:
                print("input: OpenCompleted")
                break
            case Stream.Event.hasBytesAvailable:
                print("input: HasBytesAvailable")

                print("On est connecté")

                if readChars > 0 {
                    let readString: String = NSString(data: NSData(bytes:buffer, length:readChars) as Data, encoding: String.Encoding.utf8.rawValue)! as String
                    print(readString) //  data from server
                    inputStream?.close()
                    outputStream?.close()
                }

            default:
                break
            }
        }
   }


}