如何在Rust中读写XML到TcpStream?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在Rust中读写XML到TcpStream?相关的知识,希望对你有一定的参考价值。
我正在尝试使用Rust和XML登录服务器。我在我定义的TcpStream
结构中使用了Connect
结构:
//use std::fs;
mod epp {
use crate::Config;
use std::io::Result;
use std::io::{self, Read, Write};
use std::net::TcpStream;
//use openssl::ssl::{SslMethod, SslConnector, SslStream};
pub struct Connect {
stream: TcpStream,
}
impl Connect {
pub fn new(config: Config) -> Connect {
let mut server = config.epp_test_server;
server.push_str(":49160");
let stream = TcpStream::connect(server).unwrap();
//Do an initial read to flush out responses (make way for subsequent reads).
let mut data = [0 as u8; 11024];
let result = stream.read(&mut data);
Connect { stream }
}
pub fn write_all(&mut self, buf: &[u8]) {
self.stream
.write_all(buf)
.expect("Could not write XML to SslStream");
}
pub fn flush(&mut self) {
self.stream.flush().unwrap();
}
pub fn read(&mut self, buf: &mut [u8]) -> Result<String> {
match self.stream.read(buf) {
Ok(_) => {
let text = String::from_utf8_lossy(&buf[..]);
Ok(text.to_string())
}
Err(e) => match e.kind() {
io::ErrorKind::WouldBlock => {
println!("Got WouldBlock error. There looks like nothing to read.");
Err(e)
}
_ => panic!("Got an error {}", e),
},
}
}
}
}
pub struct Config {
epp_test_server: String,
}
impl Config {
pub fn new() -> Config {
Config {
epp_test_server: String::from("139.162.247.141"),
}
}
}
fn main() {
let config: Config = Config::new();
let mut stream = epp::Connect::new(config);
//let xml = fs::read_to_string("login.xml").expect("Could not load file.");
let xml = "<?xml version="1.0" encoding="UTF-8"?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:ietf:params:xml:ns:epp-1.0 epp-1.0.xsd">
<command>
<login>
<clID>**TAG**</clID>
<pw>**Password**</pw>
<options>
<version>1.0</version>
<lang>en</lang>
</options>
<svcs>
<objURI>urn:ietf:params:xml:ns:domain-1.0</objURI>
<objURI>urn:ietf:params:xml:ns:contact-1.0</objURI>
<objURI>urn:ietf:params:xml:ns:host-1.0</objURI>
</svcs>
</login>
<clTRID>ABC-12345</clTRID>
</command></epp>";
xml = format!("{}
", xml);
stream.write_all(xml.as_bytes());
stream.flush();
let mut data = [0 as u8; 11024];
let result = stream.read(&mut data).unwrap();
println!("EPP Query result: {}", result);
}
似乎写得很好,但我没有得到想要的答复。可以使用netcat(在服务器139.162.247.141端口49160上)-nc -l 139.162.247.141 49160
演示写入功能。
我正在尝试使用Rust和XML登录服务器。我在定义的Connect结构中使用TcpStream结构://使用std :: fs; mod epp {使用crate :: Config;使用std :: io :: Result;使用...
答案
我只是在进行连接时准备进行初始读取,以准备后续读取的流。我添加了:
以上是关于如何在Rust中读写XML到TcpStream?的主要内容,如果未能解决你的问题,请参考以下文章