IOS socket连接 swift

2017-08-07  本文已影响0人  huxq_coder

使用CocoaAsyncSocket

https://github.com/robbiehanson/CocoaAsyncSocket

server端

Simulator Screen Shot 2017年8月7日 14.35.26.png
import UIKit
import CocoaAsyncSocket

class UIViewController: GCDAsyncSocketDelegate {
    
    @IBOutlet weak var sendMsgTextField: UITextField!
    @IBOutlet weak var portTextField: UITextField!
    @IBOutlet weak var messageTextView: UITextView!
    ///server端监听
    var serverSocket: GCDAsyncSocket?
    ///client端发送
    var clientSocket: GCDAsyncSocket?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    ///添加监听端口
    @IBAction func listenAction(_ sender: Any) {
        serverSocket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
        do {
            try serverSocket?.accept(onPort: UInt16(portTextField.text!)!)
            addMessage(message: "添加监听")
        } catch {
            addMessage(message: "监听失败")
        }
    }
    ///发送消息
    @IBAction func sendAction(_ sender: Any) {
        let data = sendMsgTextField.text?.data(using: String.Encoding.utf8)
        clientSocket?.write(data!, withTimeout: -1, tag: 0)
    }
    ///新连接建立
    func socket(_ sock: GCDAsyncSocket, didAcceptNewSocket newSocket: GCDAsyncSocket) {
        addMessage(message: "新连接")
        addMessage(message: "地址:\(String(describing: newSocket.connectedHost))")
        addMessage(message: "端口号:\(newSocket.connectedPort)")
        clientSocket = newSocket
        clientSocket?.readData(withTimeout: -1, tag: 0)
    }
    ///发送消息
    func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
        let message = String(data: data, encoding: String.Encoding.utf8)
        addMessage(message: message!)
        sock.readData(withTimeout: -1, tag: 0)
    }
    
    func addMessage(message: String) {
        messageTextView.text = messageTextView.text.appendingFormat("%@\n", message)
    }
}

client端

Simulator Screen Shot 2017年8月7日 14.36.00.png
import UIKit
import CocoaAsyncSocket

class UIViewController: GCDAsyncSocketDelegate {
    
    @IBOutlet weak var iPAddTextField: UITextField!
    @IBOutlet weak var portTextField: UITextField!
    @IBOutlet weak var messageTextView: UITextView!
    @IBOutlet weak var sendMessage: UITextView!
    
    var socket: GCDAsyncSocket?
    
    @IBAction func closeAction(_ sender: UIButton) {
        socket?.disconnect()
        addMessage(message: "断开连接")
    }
    /// 连接
    @IBAction func connectAction(_ sender: UIButton) {
        socket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
        do {
            try socket?.connect(toHost: self.iPAddTextField.text!, onPort: UInt16(self.portTextField.text!)!)
            addMessage(message: "连接成功")
        } catch _ {
            addMessage(message: "连接失败")
        }
    }
    /// 发送消息
    @IBAction func sendAction(_ sender: UIButton) {
        socket?.write(sendMessage.text.data(using: String.Encoding.utf8)!, withTimeout: -1, tag: 0)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    /// 已连接
    func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
        addMessage(message: "连接服务器 \(host):\(port)")
        socket?.readData(withTimeout: -1, tag: 0)
    }
    /// 返回数据
    func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
        let msg = String(data: data, encoding: String.Encoding.utf8)
        addMessage(message: msg!)
        socket?.readData(withTimeout: -1, tag: 0)
    }
    
    func addMessage(message: String){
        messageTextView.text = messageTextView.text.appendingFormat("%@\n", message)
    }
    
}
上一篇下一篇

猜你喜欢

热点阅读