1 功能需求:
1 在Swift下使用GCDAsyncSocket实现简单的信息收发功能
2 Mac下为tcp客户端,windows下为tcp服务器
2 效果图:
3 swift代码:需要导入GCDAsyncSocket库文件,可去github下载
import UIKit
class ViewController: UIViewController,GCDAsyncSocketDelegate {
@IBOutlet var serveripInput: UITextField!
@IBOutlet var msgInput: UITextField!
@IBOutlet var conBtn: UIButton!
@IBOutlet var sendBtn: UIButton!
@IBOutlet var msgView: UITextView!
let serverPort: UInt16 = 9050
var clientSocket: GCDAsyncSocket!
var mainQueue = dispatch_get_main_queue()
override func viewDidLoad() {
super.viewDidLoad()
}
//连接服务器按钮事件
@IBAction func conBtnClick(sender: AnyObject) {
do {
clientSocket = GCDAsyncSocket()
clientSocket.delegate = self
clientSocket.delegateQueue = dispatch_get_global_queue(0,0)
try clientSocket.connectToHost(serveripInput.text!,onPort: serverPort)
conBtn.backgroundColor = UIColor.blueColor()
}
catch {
print("error")
conBtn.backgroundColor = UIColor.redColor()
}
}
func socket(sock: GCDAsyncSocket!,didConnectToHost host: String!,port: UInt16) {
print("与服务器连接成功!")
clientSocket.readDataWithTimeout(-1,tag: 0)
}
func socketDidDisconnect(sock: GCDAsyncSocket!,withError err: NSError!) {
print("与服务器断开连接")
}
func socket(sock: GCDAsyncSocket!,didReadData data: NSData!,withTag tag: Int) {
// 1 获取客户的发来的数据 ,把 NSData 转 NSString
let readClientDataString: NSString? = NSString(data: data,encoding: NSUTF8StringEncoding)
print(readClientDataString!)
// 2 主界面ui 显示数据
dispatch_async(mainQueue,{
let showStr: NSMutableString = NSMutableString()
showStr.appendString(self.msgView.text)
showStr.appendString(readClientDataString! as String)
showStr.appendString("\n")
self.msgView.text = showStr as String
})
// 3.处理请求,返回数据给客户端 ok
let serviceStr: NSMutableString = NSMutableString()
serviceStr.appendString("ok\n")
clientSocket.writeData(serviceStr.dataUsingEncoding(NSUTF8StringEncoding),withTimeout: -1,tag: 0)
clientSocket.readDataWithTimeout(-1,tag: 0)
}
//发送消息按钮事件
@IBAction func sendBtnClick(sender: AnyObject) {
// 1.处理请求,返回数据给客户端 ok
let serviceStr: NSMutableString = NSMutableString()
serviceStr.appendString(self.msgInput.text!)
serviceStr.appendString("\n")
clientSocket.writeData(serviceStr.dataUsingEncoding(NSUTF8StringEncoding),tag: 0)
}
}
原文链接:https://www.f2er.com/swift/323897.html