Sockets, part 3 (nonblocking tcp using streams) Eric Freudenthal
Calls for stream sockets Socket(): to create Bind(): to associate with a port, or port & addr Listen(): set a socket in a mode where it can accept Accept(): provides a socket connected to a client Connect(): to connect to a server socket Read, Write(): to send/obtain data Readv, Writev Close(): Disconnect socket Shutdown(): done with transmit or receive Set non-blocking (actually a bit messy) Poll(): wait for condition
Simple request/response lifecycle Server listener Client stream Set non-blocking Set non-blocking Connect Listen (POLLIN) Accept sever socket (POLLOUT) Accepted (server) stream Write (part of) request Set non-blocking (POLLIN) no Done? Read (part of) request Shutdown(SHUT_WR) no Zero length? (POLLOUT) Write (part of) response (POLLIN) no Read (part of) response Done? no Close Zero length? Close
Server listener createServer() serverAction() // on POLLIN Socket(), Bind(), set non-blocking Record: socket needs POLLIN serverAction() // on POLLIN Accept() Create ServerHandler Set non-blocking Listen (POLLIN) Accept sever socket
Client createClient () clientAction() Set non-blocking Connect createClient () Socket(), non-blocking, Connect() Record: socket needs POLLOUT clientAction() If for POLLOUT Write (part of) request If done, sensitivity now POLLIN If for POLLIN Read (part of) response If zero length Unregister POLLIN Close socket Free memory (POLLOUT) Write (part of) request no Done? Shutdown(SHUT_WR) (POLLIN) Read (part of) response no Zero length? Close
Write (part of) response Client createSStream() Set non-blocking Record: socket needs POLLIN sstreamAction() If for POLLIN Read (part of) request If zero length, sensitivity now POLLOUT If for POLLOUT Write (part of) response If done Unregister POLLOUT Close socket Free memory Set non-blocking (POLLIN) Read (part of) request Zero length? (POLLOUT) Write (part of) response no Done? Close