Swift开发:GCDAsyncSocket通信之TCP 客户端

前端之家收集整理的这篇文章主要介绍了Swift开发:GCDAsyncSocket通信之TCP 客户端前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1 功能需求:

1 在Swift下使用GCDAsyncSocket实现简单的信息收发功能

2 Mac下为tcp客户端,windows下为@H_301_30@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)

// 4 每次读完数据后,都要调用一次监听数据的方法

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

猜你在找的Swift相关文章