🎓 BookMCQ
← Back to 25. Introduction to Application Layer

📝 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.
9
Easy
15
Medium
6
Hard

📝 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?

A.The second client is immediately rejected with a connection reset.
B.The server queues the second client’s request internally until the first finishes. ✅
C.The second client receives a timeout error and must retry later.
D.Both clients are served simultaneously using separate threads.
💡 Difficulty: easy | ✅ Correct: B

📖 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?

A.Application layer
B.Transport layer ✅
C.Network layer
D.Data link layer
💡 Difficulty: easy | ✅ Correct: B

📖 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 accept()accept() once, processes the client, then calls close()close(). What inference can be made about the server’s ability to handle concurrent connections?

A.It can handle many concurrent connections via multiplexing.
B.It can handle only one connection at a time.
C.It can handle multiple connections but only after they finish processing sequentially. ✅
D.It can handle connections only if they use UDP instead of TCP.
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: The pattern accept()accept() → process → close()close() 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 select()select() or non‑blocking sockets, which are absent here.

Q4. When an iterative TCP server uses select()select() to monitor multiple sockets, which of the following best describes the change in its execution model?

A.It becomes a multi‑process model.
B.It remains strictly sequential but with timeout handling.
C.It adopts an event‑driven model that can service several clients without threads. ✅
D.It switches to UDP communication for faster throughput.
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: Using select()select() 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?

A.The server will process all requests instantly.
B.The server will queue requests and process them one after another, causing client‑side back‑pressure. ✅
C.The server will drop excess requests and only process the first one.
D.The server will switch to a non‑blocking mode automatically.
💡 Difficulty: medium | ✅ Correct: B

📖 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 EWOULDBLOCKEWOULDBLOCK, thereby applying back‑pressure.

Q6. If an iterative server mistakenly calls listen()listen() with a backlog value of 0, what effect does this have on incoming connection attempts?

A.All connections are accepted immediately.
B.No connections are queued; new attempts are refused until the server calls accept()accept() again. ✅
C.The server will automatically increase the backlog to a default value.
D.The server will crash due to invalid parameters.
💡 Difficulty: hard | ✅ Correct: B

📖 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 accept()accept() state receives a connection‑refused error, effectively making the server appear unavailable during processing periods.

Q7. Consider an iterative server that never calls shutdown()shutdown() before close()close(). What deduction can be made about the reliability of data transmission to the client?

A.Data may be lost because the FIN flag is not sent. ✅
B.All data is guaranteed to be delivered before the socket is closed.
C.The client will receive an immediate reset signal.
D.The server will automatically retransmit any lost packets.
💡 Difficulty: medium | ✅ Correct: A

📖 Explanation: Calling close()close() on a TCP socket implicitly performs a graceful shutdown, sending a FIN after all queued data is transmitted. Not invoking shutdown()shutdown() 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 recv()recv() calls, what logical relationship exists between the server’s CPU utilization and the arrival rate of client data?

A.CPU usage stays high regardless of traffic.
B.CPU usage drops to near zero when no data arrives, rising only during active receives. ✅
C.CPU usage is constant because blocking calls still consume cycles.
D.CPU usage is unpredictable and unrelated to traffic patterns.
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Blocking recv()recv() 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 SOREUSEADDRSO_REUSEADDR 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?

A.The bind will fail with an address‑in‑use error. ✅
B.The bind will succeed immediately because the address is reusable.
C.The system will delay the bind for a timeout period.
D.The bind will succeed but only after a reboot.
💡 Difficulty: hard | ✅ Correct: A

📖 Explanation: The SOREUSEADDRSO_REUSEADDR 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 accept()accept() loop with a recursive function that calls accept()accept() again after processing each client. Which analytical outcome best describes this change?

A.Recursion reduces memory usage compared to iteration.
B.Recursion introduces a risk of stack overflow for many connections. ✅
C.Recursion guarantees better concurrency than threading.
D.Recursion eliminates the need for socket closure.
💡 Difficulty: easy | ✅ Correct: B

📖 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 select()select() with one that uses poll()poll(). Which statement accurately reflects a key analytical difference?

A.select()select() can handle an unlimited number of descriptors, while poll()poll() cannot.
B.poll()poll() uses a fixed‑size array, making it more memory‑efficient for large descriptor sets.
C.select()select() modifies the original descriptor set, requiring re‑initialization each loop; poll()poll() does not. ✅
D.Both functions behave identically, so there is no analytical difference.
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: select()select() overwrites the fd_set structures, so the server must repopulate them before each call, adding overhead. poll()poll() 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?

A.The server will automatically offload computation to the client.
B.Computation time will block the server from accepting new connections, reducing responsiveness. ✅
C.The server will switch to UDP to speed up processing.
D.Heavy computation has no impact on the server’s ability to accept connections.
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Because the server handles one client at a time, any lengthy computation occupies the single thread, preventing the server from invoking accept()accept() 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 SOREUSEADDRSO_REUSEADDR before binding. Which outcome best aligns with this principle?

A.It prevents any other process from ever using the same port.
B.It allows the server to bind to a port that is in a TIME_WAIT state, reducing downtime. ✅
C.It forces the kernel to allocate a new IP address for each bind.
D.It disables the TCP three‑way handshake for faster connections.
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Setting SOREUSEADDRSO_REUSEADDR 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?

A.It will drop excess packets silently.
B.It will set the window size to zero, causing the client to pause sending. ✅
C.It will increase the retransmission timeout dramatically.
D.It will switch the connection to UDP automatically.
💡 Difficulty: hard | ✅ Correct: B

📖 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 ServerSocketServerSocket. Which analytical comparison correctly identifies a key distinction?

A.The C server automatically handles character encoding, while Java does not.
B.Java’s ServerSocketServerSocket provides built‑in thread pooling, whereas the C server must implement it manually.
C.The C server must explicitly manage byte order, while Java abstracts it away. ✅
D.Both languages require identical code for socket creation.
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: In C, developers must call htons()htons() 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?

A.Large files trigger a switch to UDP, which blocks other traffic.
B.The server’s single thread is occupied reading the file, preventing it from calling accept()accept() for new connections. ✅
C.File I/O is performed in kernel space, freeing the server thread.
D.The server automatically spawns a new thread for the transfer, keeping the main loop free.
💡 Difficulty: easy | ✅ Correct: B

📖 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 accept()accept() call, other clients must wait, leading to perceived unresponsiveness.

Q17. If an iterative TCP server uses blocking accept()accept() and the network experiences a sudden surge of SYN packets, which logical outcome is most probable?

A.The server will accept all connections instantly, handling them in parallel.
B.The SYN backlog will overflow, causing some connection attempts to be dropped or delayed. ✅
C.The server will automatically switch to non‑blocking mode to cope.
D.The server will ignore the surge and continue as normal.
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: A sudden influx of SYN packets fills the kernel’s pending‑connection queue (backlog). Since the server is blocked in accept()accept() 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?

A.Logical connections eliminate the need for sockets entirely.
B.Even though the application perceives a direct link, sockets provide the underlying transport mechanisms that must be opened, read, and closed. ✅
C.Logical connections automatically handle error recovery, so sockets are only for debugging.
D.Sockets are only used for UDP, not TCP, in iterative servers.
💡 Difficulty: medium | ✅ Correct: B

📖 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 while(1)while(1) loop with a recursive function that calls accept()accept() after each client finishes. Which logical inference about program stack usage is correct?

A.The recursion will never affect stack size because accept()accept() does not allocate memory.
B.Each client handled adds a new stack frame, potentially causing stack overflow after many connections. ✅
C.Recursion reduces overall memory consumption compared to a loop.
D.The stack is automatically cleared after each close()close() call, preventing overflow.
💡 Difficulty: hard | ✅ Correct: B

📖 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 SORCVBUFSO_RCVBUF socket option to enlarge its receive buffer?

A.It eliminates the need for flow control entirely.
B.It reduces the number of context switches required for processing incoming data. ✅
C.It guarantees zero packet loss regardless of network conditions.
D.It allows the server to handle multiple clients concurrently without additional threads.
💡 Difficulty: medium | ✅ Correct: B

📖 Explanation: Increasing SORCVBUFSO_RCVBUF provides more kernel‑level storage for incoming bytes, allowing the server to read larger chunks per recv()recv() 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?

A.The speed of the TCP three‑way handshake.
B.The latency of database queries, because the server blocks while waiting for results. ✅
C.The size of the server’s executable file.
D.The number of CPU cores available on the client machine.
💡 Difficulty: medium | ✅ Correct: B

📖 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?

A.Both hosts will exchange data simultaneously without delay.
B.The communication will deadlock, as each side waits for the other to initiate. ✅
C.The hosts will automatically switch to UDP to avoid the deadlock.
D.One host will timeout and switch to a client role.
💡 Difficulty: hard | ✅ Correct: B

📖 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?

A.C uses exceptions for socket errors, while Java returns error codes.
B.Java’s IOExceptionIOException provides a unified exception mechanism, whereas C requires checking return values and errno. ✅
C.Both languages require identical try‑catch blocks for socket operations.
D.C automatically retries failed connections, while Java does not.
💡 Difficulty: medium | ✅ Correct: B

📖 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 IOExceptionIOException, enabling a more structured error‑handling flow using try‑catch blocks.

Q24. A developer adds a timeout to the server’s recv()recv() call using setsockopt()setsockopt() with SORCVTIMEOSO_RCVTIMEO. Which conceptual effect does this have on the server’s behavior?

A.The server will never block, regardless of data arrival.
B.The server will abort the connection after the timeout expires, even if data is pending.
C.The server will return from recv()recv() with an error if no data arrives within the specified interval, allowing it to perform other tasks. ✅
D.The timeout setting disables TCP’s retransmission mechanisms.
💡 Difficulty: medium | ✅ Correct: C

📖 Explanation: Setting SORCVTIMEOSO_RCVTIMEO makes recv()recv() 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 fork()fork() to handle each client in a child process, how does this change the classification of the server?

A.It remains purely iterative because each child is still single‑threaded.
B.It becomes a concurrent server, introducing parallelism at the process level. ✅
C.It converts to a peer‑to‑peer model automatically.
D.It switches to UDP communication for the children.
💡 Difficulty: easy | ✅ Correct: B

📖 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 accept()accept() without a preceding listen()listen() call, which logical outcome is expected?

A.The server will accept connections normally.
B.The server will crash due to a segmentation fault.
C.The accept()accept() call will fail with an error indicating the socket is not listening. ✅
D.The server will automatically invoke listen()listen() internally.
💡 Difficulty: hard | ✅ Correct: C

📖 Explanation: accept()accept() requires the socket to be in a listening state. Without a prior listen()listen(), 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 listen()listen() function in a TCP server?

A.It sends data to the client.
B.It binds the socket to a specific IP address.
C.It marks the socket as passive and sets the maximum length of the pending‑connection queue. ✅
D.It closes the socket after communication ends.
💡 Difficulty: easy | ✅ Correct: C

📖 Explanation: The listen()listen() 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 accept()accept().

Q28. What does the SOLINGERSO_LINGER socket option control in the context of an iterative TCP server’s shutdown process?

A.The maximum segment size for outgoing packets.
B.Whether the socket closes immediately or waits to send remaining data before closing. ✅
C.The time-to-live (TTL) of IP packets.
D.The encryption algorithm used for the connection.
💡 Difficulty: easy | ✅ Correct: B

📖 Explanation: SOLINGERSO_LINGER determines the behavior of close()close(). 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?

A.To encrypt the data payload.
B.To synchronize sequence numbers and confirm both ends are ready for communication. ✅
C.To compress the data for faster transmission.
D.To allocate IP addresses dynamically.
💡 Difficulty: easy | ✅ Correct: B

📖 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?

A.They can handle unlimited concurrent connections without additional threads.
B.They process one client request at a time, often leading to increased latency for additional clients. ✅
C.They require UDP for data transmission.
D.They automatically load‑balance across multiple servers.
💡 Difficulty: easy | ✅ Correct: B

📖 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.

🔗 Related Topics (MCQs)