I'm trying to create a server that receives a string from a client through TCP socket communication and returns the same string to the same socket. I want the following specifications:
loop
block in the code below)Ok
branch in the loop
block)"Invalid data"
( Err
branch in the loop
block)use std::io::Error;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;
#[tokio::main]
async fn main() -> Result<(), Error> {
// Create TCP listener
let addr = "localhost:8080";
let socket = TcpListener::bind(&addr).await;
let listener = socket.unwrap();
// Accept connection
let (mut socket, _addr) = listener.accept().await.unwrap();
// Split socket into read and write halves
let (reader, mut writer) = socket.split();
// Read buffer into string
let mut line = String::new();
let mut buf_reader = BufReader::new(reader);
loop {
match buf_reader.read_line(&mut line).await {
Ok(bytes) => {
if bytes == 0 {
// `bytes == 0` means the connection is closed
break;
}
}
Err(error) => {
println!("{error}");
line = "Invalid data".to_string();
}
}
// Respond to client
writer.write_all(line.as_bytes()).await.unwrap();
line.clear();
}
Ok(())
}
The client is te.net
on macOS.
telnet localhost 8080
Below are how to reproduce the issue:
"hello"
returns "hello"
."stream did not contain valid UTF-8"
on the server side and no response from the server is displayed on the te.net side (I want "Invalid data"
to be displayed)."hello"
again returns nothing, even though I have confirmed that the server is receiving it.te.net output:
hello
hello
^C
hello
Will the TcpStream
become invalid once invalid UTF-8 is received?
Invalid data
" when it receives invalid UTF-8 characters.loop
. It was an issue with te.net
. I created invalid.csv
which contains 3 rows alternating between valid and invalid rows of UTF-8 sequences:
invalid.csv
hello
(invalid UTF-8 sequences)
hello
Then, I used a pipe with nc
command:
cat invalid.csv | nc localhost 8080
The output was:
hello
Invalid data
hello
which is as expected.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.