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
use std::io::{Read, Write};
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_all(&buf[..n]).unwrap();
});
}
});§std::io trait implementations
TcpStream implements std::io::Read and std::io::Write, so it
works directly with any code that accepts impl Read or impl Write —
including BufReader, BufWriter, and Rust’s I/O adapters — without
any unsafe wrapper or raw-fd manipulation.
[TcpStream::try_clone] duplicates the underlying fd via dup(2),
yielding an independent stream that shares the same TCP connection. This
is useful for splitting a connection into separate read and write halves:
use std::io::{Read, Write};
go_lib::run(|| {
let listener = go_lib::net::TcpListener::bind("127.0.0.1:9000").unwrap();
let stream = listener.accept().unwrap();
let mut writer = stream.try_clone().unwrap();
go_lib::go!(move || {
// `stream` is the read half; `writer` is the write half.
let mut buf = [0u8; 512];
let n = (&stream).read(&mut buf).unwrap(); // via &TcpStream impl
writer.write_all(&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.