aboutsummaryrefslogtreecommitdiff
path: root/examples/tcp_server.rs
diff options
context:
space:
mode:
Diffstat (limited to 'examples/tcp_server.rs')
-rw-r--r--examples/tcp_server.rs24
1 files changed, 16 insertions, 8 deletions
diff --git a/examples/tcp_server.rs b/examples/tcp_server.rs
index dc871f3..42426ee 100644
--- a/examples/tcp_server.rs
+++ b/examples/tcp_server.rs
@@ -128,18 +128,23 @@ fn handle_connection_event(
if event.is_readable() {
let mut connection_closed = false;
- let mut received_data = Vec::with_capacity(4096);
+ let mut received_data = vec![0; 4096];
+ let mut bytes_read = 0;
// We can (maybe) read from the connection.
loop {
- let mut buf = [0; 256];
- match connection.read(&mut buf) {
+ match connection.read(&mut received_data[bytes_read..]) {
Ok(0) => {
// Reading 0 bytes means the other side has closed the
// connection or is done writing, then so are we.
connection_closed = true;
break;
}
- Ok(n) => received_data.extend_from_slice(&buf[..n]),
+ Ok(n) => {
+ bytes_read += n;
+ if bytes_read == received_data.len() {
+ received_data.resize(received_data.len() + 1024, 0);
+ }
+ }
// Would block "errors" are the OS's way of saying that the
// connection is not actually ready to perform this I/O operation.
Err(ref err) if would_block(err) => break,
@@ -149,10 +154,13 @@ fn handle_connection_event(
}
}
- if let Ok(str_buf) = from_utf8(&received_data) {
- println!("Received data: {}", str_buf.trim_end());
- } else {
- println!("Received (none UTF-8) data: {:?}", &received_data);
+ if bytes_read != 0 {
+ let received_data = &received_data[..bytes_read];
+ if let Ok(str_buf) = from_utf8(received_data) {
+ println!("Received data: {}", str_buf.trim_end());
+ } else {
+ println!("Received (none UTF-8) data: {:?}", received_data);
+ }
}
if connection_closed {