下面是我的代码。
当服务器的IP正确时,它可以完美地工作,但在IP不正确的情况下,一旦它试图发送消息,应用程序就会冻结,如果它被注释掉,然后在它试图接收时再次冻结。
我需要放置一些东西来通知用户IP不正确,而不是冻结应用程序。
我已经尝试了一个开关的情况下,我已经尝试检查。hasbytesavailable和。hasspaceavailable,这两者都返回false不管,以及其他一些建议在网上。如果有人能提供一些帮助,那就太好了。
哦,只是供参考,这都是在Swift 3
import UIKit
import Foundation
class SocketTest{
var output: NSString?
func SocketWorks(test: String) -> NSString{
output = "Hello"
let CDIP = CoreDataUDP()
let serverIP = CDIP.getIP()
var server = serverIP
var port = 5000
//var host :NSHost = NSHost(address: server)
var inp :InputStream?
var out :OutputStream?
Stream.getStreamsToHost(withName: server, port: port, inputStream: &inp, outputStream: &out)
let inputStream = inp!
let outputStream = out!
inputStream.open()
defer {
inputStream.close()
}
outputStream.open()
defer {
outputStream.close()
}
let messageSend: String = test
let messageSendCount = messageSend.characters.count
outputStream.write(messageSend, maxLength: messageSendCount)
let bufferSize = 1024
var buffer = Array<UInt8>(repeating: 0, count: bufferSize)
let bytesRead = inputStream.read(&buffer, maxLength: bufferSize)
if bytesRead >= 0 {
output = NSString(bytes: &buffer, length: bytesRead, encoding: String.Encoding.utf8.rawValue)
} else {
NSLog("Its not right yet", output!)
}
print(output!)
return output!
}
}
你应该通过实现流的委托来使用异步通信。