下載位置:https://github.com/robbiehanson/CocoaAsyncSocket
使用 AsyncUdpSocket.m 和 AsyncUdpSocket.h
因為專案是 Swift 專案,要使用 objecitive-c 的函式庫要在 Header 檔中 import。
1. 複製 AsyncUdpSocket.m 和 AsyncUdpSocket.h 到專案中,xcode 會問你是否建立 Bridge file,確定建立。
2. 在 你的專案名稱-Bridging-Header.h 檔中加入:
1
|
#import "AsyncUdpSocket.h" |
ViewControler.swift
//
// ViewController.swift
// udp_test
//
// Created by on 16/5/9.
// Copyright © 2016年. All rights reserved.
//
import UIKit
class ViewController: UIViewController,AsyncUdpSocketDelegate{
var udpClient = AsyncUdpSocket();
override func viewDidLoad() {
super.viewDidLoad();
// Do any additional setup after loading the view, typically from a nib.
}
//手动发送
@IBAction func btn_send(sender: UIButton) {
let data = "Hi, im wang".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true);
udpClient.sendData(data, toHost: "192.168.1.102", port: 60002, withTimeout: -1, tag: 0);
//开始监听接收,并如10秒内无消息回复就自动断开连接,只接收一次,//如果设置超时为-1 则没有超时限制
udpClient.receiveWithTimeout(10, tag: 0);
}
//手动关闭连接
@IBAction func close(sender: UIButton) {
udpClient.close();
}
//手动连接
@IBAction func btn_conn(sender: UIButton) {
udpClient = AsyncUdpSocket(delegate: self);
}
//如果本地发送成功 监听
func onUdpSocket(sock: AsyncUdpSocket!, didSendDataWithTag tag: Int) {
print("send success");
}
//监听接收
func onUdpSocket(sock: AsyncUdpSocket!, didReceiveData data: NSData!, withTag tag: Int, fromHost host: String!, port: UInt16) -> Bool {
let str = NSString(data: data, encoding: NSUTF8StringEncoding);
print("receive:\(str)");
//如果不能一次接收完还有更多的
udpClient.receiveWithTimeout(10, tag: 0);
return true;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//
import UIKit
class ViewController: UIViewController,AsyncUdpSocketDelegate{
var udpClient = AsyncUdpSocket();
override func viewDidLoad() {
super.viewDidLoad();
// Do any additional setup after loading the view, typically from a nib.
}
//手动发送
@IBAction func btn_send(sender: UIButton) {
let data = "Hi, im wang".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true);
udpClient.sendData(data, toHost: "192.168.1.102", port: 60002, withTimeout: -1, tag: 0);
//开始监听接收,并如10秒内无消息回复就自动断开连接,只接收一次,//如果设置超时为-1 则没有超时限制
udpClient.receiveWithTimeout(-1, tag: 0);
}
//手动关闭连接
@IBAction func close(sender: UIButton) {
udpClient.close();
}
//手动连接
@IBAction func btn_conn(sender: UIButton) {
udpClient = AsyncUdpSocket(delegate: self);
}
//如果本地发送成功 监听
func onUdpSocket(sock: AsyncUdpSocket!, didSendDataWithTag tag: Int) {
print("send success");
}
//监听接收
func onUdpSocket(sock: AsyncUdpSocket!, didReceiveData data: NSData!, withTag tag: Int, fromHost host: String!, port: UInt16) -> Bool {
let str = NSString(data: data, encoding: NSUTF8StringEncoding);
print("receive:\(str)");
//如果不能一次接收完还有更多的
udpClient.receiveWithTimeout(-1, tag: 0);
return true;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}