Socket programming¶
Socket programming is a network programming technique that utilizes the Socket API, originally a BSD UNIX API, to enable communication between applications.^[600-developer__java__java-io__java-socket.md]
The primary purpose of socket programming is to abstract the complexity of underlying network layers. By using this interface, application developers can focus on application-layer logic without needing to manage the details of the transport layer or network layer.^[600-developer__java__java-io__java-socket.md]
Message Framing and Parsing¶
In application protocol design, socket programming requires defining how messages are framed (delimited) and parsed. Common strategies include:
- Delimiter-based: Messages end with a unique marking sequence. This is often used for text-based encoding. Care must be taken to ensure the data itself does not mimic the delimiter, or techniques like bit-stuffing must be used.^[600-developer__java__java-io__java-socket.md]
- Explicit Length: A fixed-size field is prepended to a variable-length message to indicate its byte size. This approach is typically used for binary encoding.^[600-developer__java__java-io__java-socket.md]
I/O Models¶
Socket programming often employs specific I/O models to handle multiple connections efficiently:
- Select Model: Uses the
selectsystem call to monitor multiple file descriptors to see if any are ready for reading/writing.^[600-developer__java__java-io__java-socket.md] - Epoll Model: A scalable I/O event notification mechanism (primarily on Linux) that is more efficient than the traditional select model for large numbers of connections.^[600-developer__java__java-io__java-socket.md]
Zero Copy¶
A specific optimization in socket programming is Zero Copy, particularly when transferring files over a network.
- Traditional Approach: Data is read from disk into kernel space, then copied to user space, and finally copied back to kernel space for the network buffer.^[600-developer__java__java-io__java-socket.md]
- Optimized Approach: Data is read directly from the file system to the network interface, reducing the number of context switches and memory copies between kernel and user space.^[600-developer__java__java-io__java-socket.md]
Related Concepts¶
Sources¶
^[600-developer__java__java-io__java-socket.md]