Swift开发:GCDAsyncUdpSocket 通信之UDP广播

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

功能需求:

发送广播,搜索设备

【在wifi下无法接收广播,原因: 路由器阻止广播】

1 使用GCDAsyncUdpSocket 实现广播

下载地址:包含tcp和udp,共4个文件http://download.csdn.net/detail/taoerit/9809540

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.

}

}

3 效果

原文链接:https://www.f2er.com/swift/321850.html

猜你在找的Swift相关文章