流套接字服务器端快速

时间:2018-09-28 07:57:37

标签: swift sockets stream

我创建了一个套接字客户端的小脚本,等待服务器消息。我的目标是建立一个相反的服务器,该服务器处于打开状态并侦听客户端消息,但它当然也会调用发送消息。我已经包括了代表,以便“收听”新消息。任何想法 ?谢谢!

import UIKit

class ViewController: UIViewController, StreamDelegate {

    struct connectionStream {
        static var inp :InputStream?
        static var out :OutputStream?
    }

    var inputStream: InputStream!
    var outputStream: OutputStream!

    override func viewDidLoad() {
        super.viewDidLoad()

        let addr = "127.0.0.1"
        let port = 12345

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

        inputStream = connectionStream.inp!
        outputStream = connectionStream.out!

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

        self.inputStream.schedule(in: RunLoop.current, forMode: RunLoop.Mode.default)
        self.outputStream.schedule(in: RunLoop.current, forMode: RunLoop.Mode.default)

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



    }

    @IBAction func messageToHololens(_ sender: Any) {
        self.sendToHololens("Hello Hololens")
    }


    func sendToHololens(_ messageValue : String) {

        let length_message = messageValue.count

        self.outputStream!.write(messageValue, maxLength: length_message)

        print("message envoyé")

    }

    func disconnect() {
        self.inputStream.close()
        self.outputStream.close()
    }

    func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
        if aStream === inputStream {
            switch eventCode {
            case Stream.Event.openCompleted:
                print("client accepté")

            case Stream.Event.hasBytesAvailable:
                var buffer = [UInt8](repeating: 0, count: 4096)

                while (self.inputStream.hasBytesAvailable){
                    let len = self.inputStream.read(&buffer, maxLength: buffer.count)
                    if(len > 0){
                        let output = NSString(bytes: &buffer, length: len, encoding: String.Encoding.utf8.rawValue)
                        if (output != ""){
                            print("server said:", output!)
                        }
                    }
                }
            default:
                break
            }
        }
    }

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

}

1 个答案:

答案 0 :(得分:1)

使用CocoaAsyncSocket

import UIKit
import CocoaAsyncSocket

class ViewController: UIViewController, GCDAsyncSocketDelegate{
    let host = "127.0.0.1"
    let port:UInt16 = 7777
    var mSocket: GCDAsyncSocket!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.mSocket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
        do {
            try self.mSocket.accept(onPort: self.port)
        } catch let error {
            print(error)
        }
    }

    public func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) {
        print("Message sent")
    }
    public func socket(_ sock: GCDAsyncSocket, didAcceptNewSocket newSocket: GCDAsyncSocket) {
        print("client accepted!!!!")

    }

    @IBAction func sendMessage(_ sender: Any) {

        let strData = "Hi"
        let closedString: String = strData + "\n"
        let data: Data = closedString.data(using: String.Encoding.utf8)!
        self.mSocket!.write(data, withTimeout: -1.0, tag: 1)

        self.mSocket!.readData(withTimeout: 1.0, tag: 0)

    }

}