下面是我的代码。
当服务器的IP正确时,它可以正常工作,但是在ip不正确的情况下,一旦尝试发送消息,应用程序就会冻结,如果已经注释掉,那么当它尝试时接收。
我需要做一些事情来告知用户IP不正确,而不是冻结应用程序。
我试过一个switch case,我试过检查.hasBytesAvailable和.hasSpaceAvailable,无论如何都返回false,以及网上的其他一些建议。如果有人能提供一些很棒的帮助。
哦,只是一个FYI,这一切都在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!
}
}