功能需求:
发送广播,搜索设备
【在wifi下无法接收广播,原因: 路由器阻止广播】
1 使用GCDAsyncUdpSocket 实现广播
2 Swift Code:
//
// ViewController.swift
// 3-SwiftSocket-udp
// Created by 黄涛 on 17/4/10.
// Copyright © 2017年 huangtao. All rights reserved.
//
import UIKit
class ViewController:UIViewController,GCDAsyncUdpSocketDelegate {
@IBOutletweakvar btnStart:UIButton!
@IBOutletweakvar lbRecvMsg:UITextView!
var mainQueue =dispatch_get_main_queue()
var udp:GCDAsyncUdpSocket!;
let localPort:UInt16 =54321;
let boardcasePort:UInt16 =1001;
overridefunc viewDidLoad() {
super.viewDidLoad()
btnStart.addTarget(self,action:"btnStartClickFun",forControlEvents:UIControlEvents.TouchUpInside)
udp =GCDAsyncUdpSocket(delegate:self,delegateQueue:dispatch_get_main_queue());
do
{
tryudp.enableBroadcast(true)
tryudp.bindToPort(localPort,interface:udpError);
tryudp.beginReceiving();
}
catch{
print("catch:\(udpError)")
}
}
var udpError:String?;
func btnStartClickFun(){
//开始广播
udp.sendData("#SYSTEM\n".dataUsingEncoding(NSUTF8StringEncoding),toHost: "255.255.255.255",port:boardcasePort,withTimeout: -1,tag:0);
}
func udpSocket(sock:GCDAsyncUdpSocket!,didReceiveData data:NSData!,fromAddress address:NSData!,withFilterContext filterContext:AnyObject!) {
let recv:NSString =NSString(data: data,encoding:NSUTF8StringEncoding)!;
// 2 主界面ui显示数据
dispatch_async(mainQueue,{
let showStr:NSMutableString =NSMutableString()
showStr.appendString(recvasString)
showStr.appendString("\n")
self.lbRecvMsg.text = showStrasString;
})
}
func udpSocket(sock:GCDAsyncUdpSocket!,didNotConnect error:NSError!) {
print("连接失败:\(error)")
}
func udpSocket(sock:GCDAsyncUdpSocket!,didSendDataWithTag tag:Int) {
print("已经发送数据:\(tag)")
}
func udpSocketDidClose(sock:GCDAsyncUdpSocket!,withError error:NSError!) {
print("断开连接 error:\(error)")
}
func udpSocket(sock:GCDAsyncUdpSocket!,didConnectToAddress address:NSData!) {
print("开始连接")
}
overridefunc didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}