我正在寻找创建一个小的Swift工具来管理我的Rust服务器。经过多次尝试,我无法与RCON server进行交流。
我可以成功使用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)
}
}