1 功能需求:
1 在Swift下使用GCDAsyncSocket实现简单的信息收发功能
2 Mac下为tcp服务器,windows下为tcp客户端
2 效果图:
3 swift代码:需要导入GCDAsyncSocket库文件,可去github下载
import UIKit
class ViewController:UIViewController,GCDAsyncSocketDelegate {
@IBOutlet var startBtn:UIButton!
@IBOutlet var msgTextView:UITextView!
var serverSocket: GCDAsyncSocket!
let serverPort: UInt16 =9050
var clientSockets: NSMutableArray!
var startIsSuccessful = false
var mainQueue =dispatch_get_main_queue()
@IBOutlet var inputTextInput:UITextField!
@IBOutlet var sendBtn:UIButton!
override func viewDidLoad() {
super.viewDidLoad()
clientSockets =NSMutableArray()
msgTextView.backgroundColor =UIColor.grayColor()
msgTextView.text ="接收的客户端消息:\n"
}
// 发送消息按钮
@IBAction func sendBtnClick(sender:AnyObject) {
if clientSockets.count ==0 {
return
}
let msg = inputTextInput.text!
// 1.处理请求,返回数据给客户端 ok
let serviceStr:NSMutableString = NSMutableString()
serviceStr.appendString(msg)
serviceStr.appendString("\n")
let wSocket = clientSockets[0]// 此处只使用一个客户端连接
wSocket.writeData(serviceStr.dataUsingEncoding(NSUTF8StringEncoding),withTimeout: -1,tag: 0)
}
//开启服务按钮
@IBAction func startServer(sender:AnyObject) {
// 1 初始化 我是mac
serverSocket =GCDAsyncSocket()
// 2 设置委托
serverSocket.delegate =self
serverSocket.delegateQueue =dispatch_get_global_queue(0,00)
do {
tryserverSocket.acceptOnPort(serverPort)
startIsSuccessful =true
self.startBtn.enabled =false
print("server start successful!")
}
catch {
startBtn.backgroundColor =UIColor.redColor()
print("server start error!")
}
}
/*
* 有客户端的socket连接到服务器
*/
func socket(srvSocket: GCDAsyncSocket!,didAcceptNewSocket cSocket: GCDAsyncSocket!) {
// 1 保存socket: 判断socket是否存在,不存在就添加
if cSocket == nil {
print("client sock nil")
return
}
if clientSockets.containsObject(cSocket) {
print("已经存在!")
return
}
else {
// 不存在,添加
clientSockets.addObject(cSocket)
}
// 2 返回消息
let serviceStr:NSMutableString = NSMutableString()
serviceStr.appendString("login successful\n")
cSocket.writeData(serviceStr.dataUsingEncoding(NSUTF8StringEncoding),tag: 0)
// 3.监听客户端有没有数据上传
//timeout -1 代表不超时
//tag 标识作用,现在不用,就写0
cSocket.readDataWithTimeout(-1,tag:0)
}
/*
* 读取客户端请求的数据
*/
func socket(cSocket: 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.msgTextView.text)
showStr.appendString(readClientDataString!as String)
showStr.appendString("\n")
self.msgTextView.text = showStras String
})
// 3.处理请求,返回数据给客户端 ok
let serviceStr:NSMutableString = NSMutableString()
serviceStr.appendString("ok\n")
cSocket.writeData(serviceStr.dataUsingEncoding(NSUTF8StringEncoding),tag: 0)
cSocket.readDataWithTimeout(-1,tag:0)
}
}