下載位置:https://github.com/robbiehanson/CocoaAsyncSocket
使用 AsyncSocket.h 及 AsyncSocket.m
因為專案是 swift 專案,要使用 objecitive-c 的函式庫要在 Header 檔中 import。
1. 複製 AsyncSocket.m 及 AsyncSocket.h 到專案中,xcode 會問你是否建立 Bridge file,確定建立。
2. 在 你的專案名稱-Bridging-Header.h 檔中加入:
1
|
#
import
"AsyncSocket.h"
|
ViewControler.swift
//
// ViewController.swift
// weixin_t1
//
// Created by on 16/5/8.
// Copyright © 2016年 . All rights reserved.
//
import UIKit
class ViewController: UIViewController,AsyncSocketDelegate {
//手动发送
@IBAction func btn_send(sender: UIButton) {
let bytearr:[UInt8] = [5,6,7];
let data: NSData = NSData(bytes: bytearr, length: bytearr.count);
//send data
socket.writeData(data, withTimeout: 0, tag: 0);
print("has send hand");
//开始监听接收,并如10秒内无消息回复就自动断开连接,只接收一次,
socket.readDataWithTimeout(10, tag: 0);
//如果设置超时为-1 则没有超时限制
//socket.readDataWithTimeout(-1, tag: 0);
}
//手动断开
@IBAction func btn_discon(sender: UIButton) {
socket.disconnect();
print("手动点击了断开");
}
//手动连接
@IBAction func btn_conn(sender: UIButton) {
socket = AsyncSocket(delegate: self);
do{
try socket.connectToHost("192.168.1.102", onPort: 60000);
}catch let error as NSError{
print(error);
}
print("连接成功");
}
var socket: AsyncSocket!;
override func viewDidLoad() {
super.viewDidLoad();
// Do any additional setup after loading the view, typically from a nib.
}
//当连接建立后调用
func onSocket(sock: AsyncSocket!, didConnectToHost host: String!, port: UInt16) {
print("has connect");
}
//当有回调调用
func onSocket(sock: AsyncSocket!, didReadData data: NSData!, withTag tag: Int) {
print("has receive");
print("data:\(data.length)");
//如果不能一次接收完还有更多的
socket.readDataWithTimeout(10, tag: 0);
//如果设置超时为-1 则没有超时限制
//socket.readDataWithTimeout(-1, tag: 0);
}
//当断开连接调用
func onSocketDidDisconnect(sock: AsyncSocket!) {
print("has disconnect");
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}