Swift3.0 — CocoaAsyncSocket客户端(Socket通信)
CocoaAsyncSocket直接从GitHub下载:
https://github.com/robbiehanson/CocoaAsyncSocket
怎么使用CocoaAsyncSocket呢?
我用的是最直接的方法,下载下来解压后是下面的文件,找到这两个文件,我们用GCDAsyncSocket(TCP),直接将这两个文件拖进xCode8
将这两个文件拖进xCode后它会提示你是否建立一个Bridge-Header,就点击Create。
然后点击这个头文件并输入
#import "GCDAsyncSocket.h"
- 1
这时候按下Command+B重新编译一下。这样CocoaAsyncSocket就导入完毕了。
下面是客户端界面
进入ViewController.swift
//
// ViewController.swift
// AsyncSocket_Exp
//
// Created by 大老虎 on 2016/11/27.
// Copyright © 2016年 Tiger. All rights reserved.
//
import UIKit
class ViewController: UIViewController, GCDAsyncSocketDelegate {
@IBOutlet weak var serveripInput: UITextField!
@IBOutlet weak var msgInput: UITextField!
@IBOutlet weak var conBtn: UIButton!
@IBOutlet weak var sendBtn: UIButton!
@IBOutlet weak var msgView: UITextView!
let serverPort: UInt16 = 6666
var clientSocket:GCDAsyncSocket!
override func viewDidLoad() {
super.viewDidLoad()
sendBtn.isEnabled = false // Socket未连接成功时发送按钮不能用
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 连接服务器按钮事件
@IBAction func conBtnClick(_ sender: AnyObject) {
if serveripInput.text?.isEmpty == false { // 如果IP地址不为空则开始连接Socket
clientSocket = GCDAsyncSocket()
clientSocket.delegate = self
clientSocket.delegateQueue = DispatchQueue.global()
do {
try clientSocket.connect(toHost: serveripInput.text!, onPort: serverPort)
} catch {
print("try connect error: \(error)")
conBtn.backgroundColor = UIColor.red
}
} else {
msgView.insertText("IP地址不能为空!\n")
}
}
func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) -> Void {
print("connect success")
sendBtn.isEnabled = true // 连接成功后发送按钮设为可用
clientSocket.readData(withTimeout: -1, tag: 0)
}
func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) -> Void {
print("connect error: \(err)")
}
func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) -> Void {
// 1、获取客户端发来的数据,把 NSData 转 NSString
let readClientDataString: NSString? = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue)
print("---Data Recv---")
print(readClientDataString)
// 2、主界面UI显示数据
DispatchQueue.main.async {
let showStr: NSMutableString = NSMutableString()
showStr.append(self.msgView.text)
showStr.append(readClientDataString! as String)
showStr.append("\r\n")
self.msgView.text = showStr as String
}
// 3、处理请求,返回数据给客户端OK
let serviceStr: NSMutableString = NSMutableString()
serviceStr.append("OK")
serviceStr.append("\r\n")
clientSocket.write(serviceStr.data(using: String.Encoding.utf8.rawValue)!, withTimeout: -1, tag: 0)
// 4、每次读完数据后,都要调用一次监听数据的方法
clientSocket.readData(withTimeout: -1, tag: 0)
}
// 发送消息按钮事件
@IBAction func sendBtnClick(_ sender: AnyObject) {
if msgInput.text?.isEmpty == false { // 如果消息不为空则发送
let serviceStr: NSMutableString = NSMutableString()
serviceStr.append(self.msgInput.text!)
serviceStr.append("\r\n")
clientSocket.write(serviceStr.data(using: String.Encoding.utf8.rawValue)!, withTimeout: -1, tag: 0)
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
到这里客户端程序就完成了,可以用iOS模拟器来跑一下。
SocketTool截图为
posted on 2018-01-09 18:17 yucaijiang 阅读(2091) 评论(0) 编辑 收藏 举报