我使用SwiftSocket将iPad上的TCP消息发送到本地设备。
第一条消息收到正确,但当我尝试发送另一条消息时,出现connectionTimeout
错误。
有什么想法吗?
Swift 3代码:
func sendMessage(_ message: String) {
self.client = TCPClient(address: "192.168.0.16", port: 7777)
switch self.client.connect(timeout: 1) {
case .success:
switch self.client.send(string: "\(message)\n") {
case .success:
print("success")
case .failure(let error):
print("Sending error: \(error)")
}
case .failure(let error):
print("Connection error: \(error)")
}
}
CLI中用于侦听消息的代码:
nc -l 192.168.0.16 7777
答案 0 :(得分:1)
试试这个课程
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)
}
}
}
}