CocoaAsyncSocket___TcpServer服务端
//
// TcpServerManager.swift
// tcp-swift
//
// Created by ma c on 2019/2/21.
// Copyright © 2019年 ma c. All rights reserved.
//
import Foundation
import Foundation
import CocoaAsyncSocket
typealias ZZWTcpServerManagerBlock = (_ isconnection:Bool) -> Void
typealias ZZWTcpServerManagerDidReceiveDataBlock = (_ receiveString:String) -> Void
class TcpServerManager: NSObject {
static let port:UInt16 = 12345
var tcpServerManagerDidReceiveDataBlock:ZZWTcpServerManagerDidReceiveDataBlock?
var tcpServerManagerBlock:ZZWTcpServerManagerBlock?
static let shared = TcpServerManager()
var tcpServerManger:GCDAsyncSocket?
var connectedSockets : NSMutableArray = NSMutableArray.init(capacity: 1)
var sourcedata :Data = Data(capacity: 0)
static let tcpError:String = "tcp,error"
var isReceiveData = false
func setTcpSocketManager() {
tcpServerManger = GCDAsyncSocket(delegate: self , delegateQueue: DispatchQueue.global(qos: .default))
tcpServerManger?.autoDisconnectOnClosedReadStream = false
}
func tryOpenTcpServer(_ tcpPort:UInt16 = port) -> TcpServerManager{
do{
try tcpServerManger?.accept(onPort: tcpPort)
}catch{
print("catch:\(String(describing: TcpServerManager.tcpError))")
}
return self
}
func tcpSocketManagerBlockFunction(tcpSocketManagerB:@escaping ZZWTcpServerManagerBlock){
tcpServerManagerBlock = tcpSocketManagerB
}
func tcpSocketDidReceiveDataBlockFunction(tcpSocketManagerB:@escaping ZZWTcpServerManagerDidReceiveDataBlock){
tcpServerManagerDidReceiveDataBlock = tcpSocketManagerB
}
}
extension TcpServerManager : GCDAsyncSocketDelegate{
func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) {
sock.readData(withTimeout: -1, tag: 0)
}
func socket(_ sock: GCDAsyncSocket, didAcceptNewSocket newSocket: GCDAsyncSocket) {
connectedSockets.add(newSocket)
let host : String = newSocket.connectedHost!
let port : UInt16 = newSocket.connectedPort
print(String(format: "Accepted client %@:%hu", host, port))
newSocket.readData(withTimeout: -1, tag: 0)
}
func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
isReceiveData = true
let recv = String(data: data , encoding:String.Encoding.utf8)
self.tcpServerManagerDidReceiveDataBlock!(recv!)
if (recv?.count)! > 0 {
sock.write("Welcome!".data(using: String.Encoding.utf8)!, withTimeout: -1, tag: 0)
}
sock.readData(withTimeout: -1, tag: 0)
}
}
使用:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
TcpServerManager.shared.setTcpSocketManager()
return true
}
func startTCP() {
if !(TcpServerManager.shared.tcpServerManger?.isConnected)!{
TcpServerManager.shared.tryOpenTcpServer()
TcpServerManager.shared.tcpSocketDidReceiveDataBlockFunction {[weak self] (receiveString) in
DispatchQueue.main.async {
self?.layerText?.text = "/n" + "\(receiveString)"
}
}
}
}
网友评论