試試這個類
class SocketManager: NSObject, StreamDelegate {
var serverAddress: CFString
let serverPort: UInt32 = 6000
private var inputStream: InputStream!
private var outputStream: OutputStream!
private var connecting:Bool
init(ip:String) {
serverAddress = ip as CFString
connecting = false
super.init()
connect()
}
func disconect(){
outputStream.close()
inputStream.close()
}
func connect() {
connecting = true
while connecting {
print("connecting...")
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
CFStreamCreatePairWithSocketToHost(nil, self.serverAddress, self.serverPort, &readStream, &writeStream)
inputStream = readStream!.takeRetainedValue()
outputStream = writeStream!.takeRetainedValue()
inputStream.delegate = self
outputStream.delegate = self
inputStream.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
outputStream.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
inputStream.open()
outputStream.open()
connecting = false
}
}
public func sendMsg(msg : String){
let data = msg.data(using: String.Encoding.utf8)!
// Write to output stream:
_ = data.withUnsafeBytes { outputStream.write($0, maxLength: data.count) }
}
public func Receive(){
let bufferSize = 81600
var buffer = Array<UInt8>(repeating: 0, count: bufferSize)
let bytesRead = inputStream.read(&buffer, maxLength: bufferSize)
if bytesRead >= 0 {
let output = NSString(bytes: &buffer, length: bytesRead, encoding: String.Encoding.utf8.rawValue)
DispatchQueue.global(qos: .background).async {
GlobalFunction.GVsharedInstance.Parser(msg: output as! String)
}
}
}
}
隨着socket通信,插座通常保持打開,你向下發送多個消息。我猜測另一端仍在監聽您創建的第一個連接。我想你想拉'connect'方法離開這裏,然後存儲在屬性中的開放連接。否則,您需要每次都斷開連接,這不是非常有效。 –
@DaveWeston我怎麼就沒有想到這一點?這解決了我的問題,非常感謝! – Skoua
不客氣! –