Я хочу создать небольшой инструмент Swift для управления моими Rust серверами.После многих попыток я не могу связаться с сервером RCON .
. Я могу успешно использовать класс Stream
для подключения к серверу, но когда я пытаюсь отправить пакет,Я не получаю никаких откликов от сервера, кроме HasSpaceAvailable
.
. Я думаю, что хорошо выполнил рекомендации, касающиеся протокола, но, к сожалению, безуспешно.
let host = "..."
let port = ...
let password = "..."
var inStream: InputStream?
var outStream: OutputStream?
var buffer = [UInt8](repeating: 0, count: 200)
func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
switch eventCode {
case Stream.Event.endEncountered:
// End of connection, connection stopped by server
// Close the streams and remove from Runloop
inStream?.close()
inStream?.remove(from: RunLoop.current, forMode: .default)
outStream?.close()
outStream?.remove(from: RunLoop.current, forMode: .default)
print("End of connection, connection stopped by server")
// isConnected = false
case Stream.Event.errorOccurred:
print("ErrorOccurred")
// Error occured, failed to connect on server
// Close the streams and remove from Runloop
inStream?.close()
inStream?.remove(from: RunLoop.current, forMode: .default)
outStream?.close()
outStream?.remove(from: RunLoop.current, forMode: .default)
print("Error occured, failed to connect on server")
// isConnected = false
case Stream.Event.hasBytesAvailable:
print("bytes")
// Has bytes avaible
// Check the inStream
if aStream == inStream {
// read the stream and get into buffer
inStream!.read(&buffer, maxLength: buffer.count)
// cast buffer to string whith utf8 encoding
print(buffer)
// let bufferStr = NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue)! as String
// print(bufferStr)
}
case Stream.Event.hasSpaceAvailable:
print("HasSpaceAvailable \(outStream!.hasSpaceAvailable)")
case Stream.Event.openCompleted:
print("Connected to server")
// isConnected = true
default:
print("Unknown")
}
}
func creatRequest(id:Int,type:Int,message:String) -> Data {
let bodyData = message.data(using: .ascii, allowLossyConversion: true)!
var size = Int(littleEndian: bodyData.count + 10)
var data = Data()
data.append(Data(bytes: &size , count: 4))
data.append(id.data)
data.append(type.data)
data.append(bodyData)
data.append(0x00)
data.append(0x00)
return data
}
func send(data:Data){
var d = [UInt8](data)
print(outStream?.write(&d, maxLength: data.count))
}
func connection(){
Stream.getStreamsToHost(withName: host, port: port, inputStream: &inStream, outputStream: &outStream)
inStream?.delegate = self
outStream?.delegate = self
inStream?.schedule(in: RunLoop.current, forMode: .default)
outStream?.schedule(in: RunLoop.current, forMode: .default)
inStream?.open()
outStream?.open()
buffer = [UInt8](repeating: 0, count: 200)
}
}