📝 Iterative Programming Using TCP in Java (30 MCQs)
Sequential Connection Handling with ServerSocket
A Java iterative TCP server uses ServerSocket to wait for client connections and Socket to communicate with each accepted client. The main loop accepts one connection, processes its request and response, closes that client socket, and then accepts the next connection. The listening server socket remains open throughout normal service. That distinction allows the service to persist across many client sessions.
Creating the Listening Endpoint and Client Socket
The server constructs ServerSocket with a local port, which binds and listens for TCP connections. A client creates Socket using the server host and port. When a connection is accepted, ServerSocket.accept returns a new Socket whose input and output streams carry data for that specific client. The client and server refer to opposite ends of the same connection.
Reading Requests and Writing Stream Responses
The accepted Socket exposes an InputStream and OutputStream. The server reads the request according to the application's framing rule, processes it, and writes response bytes. It closes the connected socket when the exchange is complete, then returns to accept. TCP preserves byte order but does not preserve application message boundaries.
A Java Line-Oriented Request Service
A client connects to a Java server on port 6500 and sends a line terminated by a newline. The server wraps its input stream in a buffered reader, reads the line, writes a response through a writer, and closes the client Socket. Its ServerSocket then accepts another connection. The reader returns a complete line only after encountering its delimiter or end-of-stream.
Stream Framing and Reliable Resource Cleanup
A reader method that waits for a delimiter can reconstruct a line, whereas a raw read may return any currently available number of bytes. The server should use clear framing, handle end-of-stream, catch IOException, and close each connection with try-with-resources. A slow client can block an iterative server's next accept.
Java TCP Server Misconceptions
'ServerSocket is the connected client channel' is incorrect because accept returns the connected Socket. 'TCP read returns one request' ignores stream framing and partial reads. 'Closing a client Socket closes ServerSocket' is false because the listening endpoint has a separate object and lifecycle. The two objects represent different stages of the server's connection lifecycle.
Tracing Java TCP Server and Client Objects
For examinations, follow ServerSocket creation, accept, Socket stream access, request parsing, response writing, and resource closure. Distinguish the listening object from the accepted connection, explain how newline or length framing defines messages, and identify why a sequential server can be delayed by a client that does not finish sending. Also identify where blocking reads can delay acceptance of another client.
Java TCP Socket Class Terms
- ServerSocket - Listens for incoming TCP client connections.
- Socket - Represents an established TCP endpoint.
- accept - Waits for and returns a client connection.
- InputStream - Provides incoming bytes from a socket.
- OutputStream - Sends outgoing bytes through a socket.
- End-of-stream - Indicates that no more peer bytes will arrive.
📝 All Iterative Programming Using TCP in Java MCQs
Q1. In an iterative TCP server that handles one client at a time, what is the most likely outcome when a second client attempts to connect before the first client’s request is fully processed?
📖 Explanation: When an iterative server processes a single connection sequentially, it does not create separate threads or processes for additional clients. Consequently, the operating system’s listen queue holds the pending connection, and the server accepts it only after completing the first client’s transaction, causing the second client to wait.
Q2. If a client sends a malformed TCP segment to an iterative server, which layer is primarily responsible for detecting and discarding the segment before it reaches the application logic?
📖 Explanation: The transport layer (TCP) performs checksum verification and sequence validation. When a segment fails these checks, TCP discards it without delivering it to the application. This protection ensures that the iterative server’s application code only receives well‑formed data, preserving reliability and simplifying error handling.
Q3. Suppose an iterative server calls once, processes the client, then calls . What inference can be made about the server’s ability to handle concurrent connections?
📖 Explanation: The pattern → process → indicates a single‑threaded loop. While the server may accept many connections over its lifetime, each is handled after the previous one completes, meaning true concurrency is not achieved. Multiplexing would require or non‑blocking sockets, which are absent here.
Q4. When an iterative TCP server uses to monitor multiple sockets, which of the following best describes the change in its execution model?
📖 Explanation: Using allows the server to wait for activity on any of its sockets, processing whichever becomes ready. This event‑driven approach enables the server to interleave handling of multiple client connections within a single thread, unlike the purely sequential accept‑process‑close loop.
Q5. A client repeatedly sends requests to an iterative server without waiting for a response. Which logical consequence is most likely?
📖 Explanation: Iterative servers handle one request at a time; extra data arriving while the server is busy is buffered by the TCP stack. The client’s rapid sending fills the socket buffer, eventually causing the client’s send calls to block or return , thereby applying back‑pressure.
Q6. If an iterative server mistakenly calls with a backlog value of 0, what effect does this have on incoming connection attempts?
📖 Explanation: A backlog of 0 instructs the kernel to place no pending connections in the listen queue. Consequently, any client that arrives while the server is not in state receives a connection‑refused error, effectively making the server appear unavailable during processing periods.
Q7. Consider an iterative server that never calls before . What deduction can be made about the reliability of data transmission to the client?
📖 Explanation: Calling on a TCP socket implicitly performs a graceful shutdown, sending a FIN after all queued data is transmitted. Not invoking explicitly does not affect reliability; the kernel ensures pending data is sent before the FIN, so the transmission remains reliable.
Q8. When an iterative server uses blocking calls, what logical relationship exists between the server’s CPU utilization and the arrival rate of client data?
📖 Explanation: Blocking causes the thread to sleep while no data is available, freeing the CPU. Only when data arrives does the call return, and the CPU is used to process the payload. Hence, utilization correlates directly with incoming traffic, conserving resources during idle periods.
Q9. If a client’s TCP socket is set to and the client crashes after closing the socket, what is the most likely effect on a subsequent client that attempts to bind to the same port?
📖 Explanation: The option allows a socket to bind to an address that is in the TIME_WAIT state, which occurs after a normal close. Even if the previous process terminated abruptly, the flag permits the new bind without waiting for the timeout, ensuring rapid reuse.
Q10. A developer replaces the iterative server’s loop with a recursive function that calls again after processing each client. Which analytical outcome best describes this change?
📖 Explanation: Recursive calls add a new stack frame for each client handled. With many successive connections, the call depth grows, eventually exhausting stack space and causing a crash. Iterative loops reuse the same stack frame, making them safer for long‑running servers.
Q11. Compare an iterative TCP server that uses with one that uses . Which statement accurately reflects a key analytical difference?
📖 Explanation: overwrites the fd_set structures, so the server must repopulate them before each call, adding overhead. works with an array of pollfd structures that retain their state, making it more convenient for large numbers of sockets.
Q12. In a scenario where an iterative server processes client requests that involve heavy computation, which conceptual drawback is most significant?
📖 Explanation: Because the server handles one client at a time, any lengthy computation occupies the single thread, preventing the server from invoking on new sockets. This bottleneck degrades overall responsiveness and can cause client‑side timeouts.
Q13. Apply the principle of “socket reuse” to explain why an iterative server might set before binding. Which outcome best aligns with this principle?
📖 Explanation: Setting informs the kernel that the server is willing to bind to an address that may still be lingering in TIME_WAIT after a previous close. This reduces the wait time between restarts, ensuring higher availability without violating TCP’s safety guarantees.
Q14. A client sends a sequence of requests faster than an iterative server can process them, causing the server’s receive buffer to fill. Which logical effect will the TCP flow‑control mechanism have?
📖 Explanation: When the receive buffer is full, the server advertises a zero‑window size in its TCP acknowledgments. The client must then stop transmitting data until the window opens again, effectively throttling the flow and preventing buffer overflow.
Q15. Consider two iterative servers: one written in C using the POSIX socket API, and another in Java using . Which analytical comparison correctly identifies a key distinction?
📖 Explanation: In C, developers must call and related functions to convert numeric values to network byte order. Java’s socket classes handle this conversion internally, simplifying code and reducing the chance of endian‑related bugs.
Q16. When an iterative server receives a client’s request that includes a large file transfer, what conceptual reason explains why the server may become unresponsive to other clients?
📖 Explanation: Because the server processes one client at a time, the thread that reads the large file cannot simultaneously listen for new connections. Until the file transfer completes and the server returns to the call, other clients must wait, leading to perceived unresponsiveness.
Q17. If an iterative TCP server uses blocking and the network experiences a sudden surge of SYN packets, which logical outcome is most probable?
📖 Explanation: A sudden influx of SYN packets fills the kernel’s pending‑connection queue (backlog). Since the server is blocked in and can only dequeue one at a time, excess SYNs are dropped or result in connection‑refused errors, reducing the server’s ability to accommodate new clients.
Q18. Apply the concept of “logical connection” at the application layer to explain why an iterative TCP server still needs to manage socket descriptors explicitly. Which statement best captures this relationship?
📖 Explanation: The application layer’s logical connection is an abstraction; the actual data exchange relies on TCP sockets that encapsulate the transport details. Therefore, developers must still create, bind, listen, accept, and close sockets to realize the logical connection envisioned at the higher layer.
Q19. A programmer replaces the iterative server’s loop with a recursive function that calls after each client finishes. Which logical inference about program stack usage is correct?
📖 Explanation: Each recursive call pushes a new frame onto the call stack, and unless the function returns before the next call, the depth grows with each client. Over many connections, this unbounded growth can exhaust the stack, leading to a crash—an important risk of using recursion for server loops.
Q20. Which analytical advantage does an iterative server gain by using the socket option to enlarge its receive buffer?
📖 Explanation: Increasing provides more kernel‑level storage for incoming bytes, allowing the server to read larger chunks per call. This can lower the frequency of system calls and context switches, improving efficiency, though it does not create true concurrency.
Q21. When an iterative server processes client requests that involve reading from a database, which conceptual factor most directly impacts overall throughput?
📖 Explanation: Since the server handles one client at a time, any blocking operation—such as a database query—halts the entire server loop. Thus, query latency becomes the dominant factor limiting how quickly successive client requests can be serviced.
Q22. In a peer‑to‑peer scenario where both hosts act as iterative TCP servers, what logical consequence follows from each host waiting for the other’s request before sending its own?
📖 Explanation: If both peers adopt an iterative server stance—waiting to accept before sending—neither initiates a connection, resulting in a classic deadlock. To avoid this, one side must assume the client role, actively initiating the connection.
Q23. Compare the error‑handling strategies of an iterative TCP server written in C versus one written in Java. Which analytical difference is most accurate?
📖 Explanation: In C, socket functions return -1 on failure, and the programmer inspects errno to determine the cause. Java abstracts this with checked exceptions like , enabling a more structured error‑handling flow using try‑catch blocks.
Q24. A developer adds a timeout to the server’s call using with . Which conceptual effect does this have on the server’s behavior?
📖 Explanation: Setting makes a bounded operation: if no data is received within the timeout, the call returns -1 and errno is set to EAGAIN/EWOULDBLOCK. This enables the server to avoid indefinite blocking and to interleave other activities.
Q25. When an iterative server uses to handle each client in a child process, how does this change the classification of the server?
📖 Explanation: Spawning a child process for each client creates separate execution contexts that can run simultaneously, providing concurrency. Although each child may be iterative, the overall server architecture now supports parallel handling of multiple clients.
Q26. If an iterative server continuously calls without a preceding call, which logical outcome is expected?
📖 Explanation: requires the socket to be in a listening state. Without a prior , the kernel returns EINVAL or ENOTSOCK, causing the call to fail. The program must handle this error; otherwise, it cannot accept any client connections.
Q27. Which factual statement correctly defines the role of the function in a TCP server?
📖 Explanation: The system call transitions a bound socket into a passive listening state and specifies the backlog—the maximum number of pending connection requests the kernel will queue before the server calls .
Q28. What does the socket option control in the context of an iterative TCP server’s shutdown process?
📖 Explanation: determines the behavior of . If enabled with a non‑zero timeout, the close call blocks until all queued data is transmitted or the timeout expires; otherwise, the socket may discard unsent data and close immediately.
Q29. In TCP, what is the purpose of the three‑way handshake before data exchange begins?
📖 Explanation: The three‑way handshake (SYN, SYN‑ACK, ACK) establishes a reliable connection by agreeing on initial sequence numbers and confirming that both the client and server are prepared to exchange data, laying the foundation for ordered, error‑checked communication.
Q30. Which fact about iterative TCP servers is true?
📖 Explanation: Iterative servers follow a simple loop: accept a connection, process the request, close the connection, then repeat. This sequential handling means that while one client is being served, others must wait, which can cause higher latency compared to concurrent designs.