pw_emu: mock_emu: start listening before making the port available

There is a race condition in mock_emu because we are making the port
available (writing it to a file for clients to read) before marking
the socket as listening.

If the client gets to run after the port is written to the file but
before the TCP thread has a chance to run we would get this error:

======================================================================
ERROR: test_channel_stream (__main__.TestEmulator)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "../../pw_emu/py/tests/frontend_test.py", line 116, in test_channel_stream
    with self._emu.get_channel_stream('gdb') as _:
  File "/b/s/w/ir/x/w/co/pw_emu/py/pw_emu/frontend.py", line 256, in get_channel_stream
    return self._c().get_channel_stream(name, timeout)
  File "/b/s/w/ir/x/w/co/pw_emu/py/pw_emu/core.py", line 533, in get_channel_stream
    sock.connect((host, port))
ConnectionRefusedError: [Errno 111] Connection refused

The fix is to mark the socket for listening before writing the port to
the file.

Bug: 306155313
Test: stress --cpu 512 and run frontend_test.py 100 times without failures
Change-Id: I04d63c6271c8d3334bab3dd4713231475fd0e74d
Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/176856
Presubmit-Verified: CQ Bot Account <pigweed-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Armando Montanez <amontanez@google.com>
Commit-Queue: Auto-Submit <auto-submit@pigweed-service-accounts.iam.gserviceaccount.com>
Pigweed-Auto-Submit: Octavian Purdila <tavip@google.com>
diff --git a/pw_emu/py/mock_emu.py b/pw_emu/py/mock_emu.py
index 0d21767..1a49b2b 100644
--- a/pw_emu/py/mock_emu.py
+++ b/pw_emu/py/mock_emu.py
@@ -24,7 +24,6 @@
 
 
 def _tcp_thread(sock: socket.socket) -> None:
-    sock.listen()
     conn, _ = sock.accept()
     while True:
         data = conn.recv(1)
@@ -84,6 +83,7 @@
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         sock.bind(('localhost', 0))
         port = sock.getsockname()[1]
+        sock.listen()
         with open(os.path.join(args.working_dir, chan), 'w') as file:
             file.write(str(port))
         thread = Thread(target=_tcp_thread, args=(sock,))