Skip to main content

Module net

Module net 

Source
Expand description

Goroutine-aware TCP networking (Step 5: netpoll integration).

See net::TcpListener and net::TcpStream.

On Linux and macOS the backend is epoll / kqueue (readiness-based). On Windows the backend is I/O Completion Ports (IOCP): overlapped WSARecv/WSASend operations are issued and the goroutine parks until GetQueuedCompletionStatusEx signals completion. Goroutine-aware TCP networking.

TcpListener and TcpStream wrap non-blocking OS sockets and integrate with the go-lib scheduler via the netpoll backend (epoll on Linux, kqueue on macOS). When a socket operation would block (EAGAIN / EWOULDBLOCK), the goroutine is parked via gopark and re-enqueued by the netpoll machinery when the socket becomes ready.

§Usage

go_lib::run(|| {
    let listener = go_lib::net::TcpListener::bind("127.0.0.1:8080").unwrap();
    loop {
        let mut stream = listener.accept().unwrap();
        go_lib::go!(move || {
            let mut buf = [0u8; 1024];
            let n = stream.read(&mut buf).unwrap();
            stream.write(&buf[..n]).unwrap();
        });
    }
});

§Porting note

Go’s net package calls runtime.poll.pollDesc.waitRead / waitWrite which translate directly to netpoll_arm(fd, POLL_READ/WRITE, gp) + gopark. The same protocol is used here.

Structs§

TcpListener
A goroutine-aware TCP server socket.
TcpStream
A goroutine-aware TCP stream socket.