Skip to content

Simple TCP server #9626

Closed
Closed
@simao

Description

@simao

Hello,

I am trying to start a TCP listener using the following code:

use std::rt::io::net::tcp::TcpListener;
use std::rt::io::{Reader, Writer, Listener, Acceptor};
use std::rt::io::net::ip::{SocketAddr, Ipv4Addr};
use std::vec;
use std::str;

fn main() {
    let addr = SocketAddr {
        ip: Ipv4Addr(0, 0, 0, 0),
        port: 9090
    };

    let mut acceptor = TcpListener::bind(addr).listen().unwrap();

    println("Listener is ready");

    loop {
        let mut stream = acceptor.accept().unwrap();
        let mut buf = vec::from_elem(1, 0u8); // Use just 1 byte to debug

        loop {
            match stream.read(buf) {
                Some(count) => {
                    if count > 0 {
                        print(str::from_utf8(buf));
                    } else {
                        println("GOT NOTHING");
                        break;
                    }
                }
                None => { println("Finished"); break }
            }
        }

        stream.write(bytes!("Hello World\r\n"));

        //        println(str::from_utf8(buf));

    }
}

So the problem here is that after the server reads all the data from
the client and then it blocks on the next read waiting for more
data, while the client, in this case curl will not send any more
data.

I tried to use stream.eof but this function is not implemented and
just throws an exception.

What is the recommended way to do this while stream.eof is not
implemented?

Thank you

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions