# The Second Player Is Still Waiting

Canonical: <https://journeytocode.io/the-second-player-is-still-waiting/>

Move Each Rust Connection Into Its Own Thread

Bryce connects and starts entering commands. Ryan connects next.

His TCP handshake can finish, and the operating system can keep the connection in the listen queue. Our application does not call `accept()` again, though. It is still inside Bryce's `handle_connection()` loop.

Ryan is connected enough to wait and not connected enough to play. Beautiful.

We are going to give each accepted stream to its own worker thread so the main thread can return to `accept()` immediately.

The [`article_3` branch](https://github.com/journey-to-code-org/one-world-many-players/tree/article_3) has the parser and single-connection server we are starting from.

**One loop, then one worker per client**

With one blocking connection loop, Bryce's handler keeps the application from returning to `accept()`. Ryan's connection may wait in the operating system's listen queue, but no handler reads Ryan's `look` command. When each accepted `TcpStream` moves into a worker thread, the main loop returns to `accept()` and both handlers can read independently.

[Try the interactive Multiplayer server simulator on the canonical article](https://journeytocode.io/the-second-player-is-still-waiting/#ob-live-one-loop-then-one-worker-per-client).


## Our starting point

The server currently accepts one stream and hands it to the blocking connection loop:

```rust
let (stream, address) = listener.accept()?;
println!("Connected: {address}");
handle_connection(stream)
```


Nothing calls `accept()` again until that handler returns. We will keep `handle_connection()` as it is and change who owns the accepted stream.

## Accept forever

Change `main()` in `src/bin/server.rs`:

**src/bin/server.rs**

```rust
use std::io;
use std::net::TcpListener;
use std::thread;

fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:4000")?;
    println!("Server listening on 127.0.0.1:4000");

    for connection in listener.incoming() {
        match connection {
            Ok(stream) => {
                let address = stream.peer_addr()?;
                println!("Connected: {address}");

                thread::spawn(move || {
                    if let Err(error) = handle_connection(stream) {
                        eprintln!("Connection {address} failed: {error}");
                    }
                });
            }
            Err(error) => eprintln!("Accept failed: {error}"),
        }
    }

    Ok(())
}
```


`listener.incoming()` produces each connection as a `Result<TcpStream>`. The loop does not end after the first player anymore.

`thread::spawn()` accepts a closure, which is a function-like value we can create in place. The new part is `move`:

```rust
thread::spawn(move || handle_connection(stream));
```


The worker may outlive the current trip through the accept loop. A borrow of the local `stream` would not be safe, because that local binding is about to go away. `move` transfers ownership of every captured value the closure needs, including the `TcpStream`, into the closure.

The stream does not become shared. It gets one new owner.

## Try two clients

Start the server. Open two more terminals and run the client in each one.

Bryce can remain at the prompt while Ryan sends `look`. Each connection has a blocking reader, but the readers block different worker threads. The main thread stays in the accept loop.

**Question:** Why does the spawned closure use `move`?

1. It moves the operating-system thread to another CPU
2. It gives the closure ownership of values such as the accepted stream
3. It makes the TCP connection asynchronous

**Answer:** 2. It gives the closure ownership of values such as the accepted stream

> **Explanation:** The worker may outlive the loop iteration that created it, so it must own the captured stream instead of borrowing a local binding.


## What we learned

- the accept loop should return to `accept()` quickly
- `thread::spawn()` runs a closure on another operating-system thread
- `move` transfers captured values into a closure
- every connection can still block without blocking the accept loop
- concurrent connections are not yet shared game state

Bryce and Ryan can both send commands now.

They are still playing in two separate universes.

**One connection. Shared world.**
[Join the discussion on the canonical article](https://journeytocode.io/the-second-player-is-still-waiting/#ob-discussion)
