iOS CocoaAsyncSocket 使用教程(swift3)

Bob Chang
3 min readMar 10, 2017

環境:Xcode 8.2.1, swift 3.0

這一篇是照著他人的文章跟著做一遍,只是某些部分改成了swift3的版本

原文在此:http://www.jianshu.com/p/65ea031ef49b

  1. 建立一個專案,並使用 Cocoapods 引入 CocoaAsyncSocket
pod 'CocoaAsyncSocket'

2. 為 Server 和 Client 制定UI畫面

3. Coding~ / Server 與 Client 連線的步驟

(1) [Server] 將非同步連線的 Delegate 放進主序列

serverSocket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)

(2) [Server] 然後開始監聽 Client 的請求

do {try serverSocket?.accept(onPort: UInt16(portTF.text!)!)addText(text: “监听成功”)} catch _ {addText(text: “监听失败”)}

(3) [Client] 此時 Client 一樣需要將非同步連線的 Delegate 放進主序列

socket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)

(4) [Client] 然後去向 “已知IP” 和 “port number” 的 server 請求連線

do {try socket?.connect(toHost: ipTF.text!, onPort: UInt16(portTF.text!)!)addText(text: “连接成功”)} catch _ {addText(text: “连接失败”)}

當連線成功時,會在下方的 textView 顯示,而他靠的是 addText()

func addText(text: String) {infoTV.text = infoTV.text.appendingFormat(“%@\n”, text)}

接著,傳遞文字的部分就交由 Delegate 完成

如果需要參考專案:

--

--

Bob Chang

喜歡橘子 / 認為活得快樂才是生命真理 / 互相學習求進步 / 我的部落格 https://bob910078.blogspot.com / 或是追蹤 Twitter @bob910078