How to Create a Simple TCP Listener/Server in Batch Script
A TCP listener is a program that opens a network port on a computer, listens for incoming connections, and accepts data from them. This is the fundamental building block of any server application. While batch scripting is excellent for file and process management, it has no native, built-in commands for network socket operations like listening on a port.
This guide will explain why a "pure-batch" approach is not possible and teach you the definitive, modern method for creating a simple TCP listener by calling a powerful PowerShell one-liner from your batch script. This is the only recommended approach for its reliability, power, and the fact that it uses tools already built into Windows.
The Challenge: Batch Can't Listen to Network Ports
The cmd.exe interpreter has no commands for creating network sockets, binding them to a port, or accepting connections. Any "pure-batch" script that claims to do this is actually using a workaround that is extremely limited and unreliable (like parsing the output of netstat). To create a true TCP listener, a batch script must act as a launcher, calling a more powerful tool to do the actual networking.
The Superior Method (Recommended): Using PowerShell
The correct and professional way to handle this is to call PowerShell, which has direct access to the .NET Framework's robust networking library.
This one-liner, called from a batch script, will create a simple server that listens on a port, accepts one connection, reads one line of data, and then closes.
powershell -Command "$listener = [System.Net.Sockets.TcpListener]::new('0.0.0.0', 8080); $listener.Start(); ..."
This is a complete, self-contained solution using tools already built into all modern versions of Windows.
The Alternative Method (Classic Tool): Using Netcat
For decades, the classic tool for this job has been netcat (nc.exe), the "Swiss Army knife of networking." It is extremely powerful but is not included with Windows by default. You must download it separately.
Syntax: nc -l -p 8080
-l: Listen for incoming connections.-p 8080: Listen on port8080.
Basic Example: A Simple "Echo Server"
This script uses the recommended PowerShell method to start a listener on port 8080. When you connect to it, it will read one line of text you send, display it on the server's console, and then shut down.
@ECHO OFF
SET "PORT=8080"
ECHO --- Simple TCP Echo Server ---
ECHO Listening on port %PORT%...
ECHO Open another command prompt and type: telnet localhost %PORT%
ECHO Then, type a message and press Enter.
ECHO Press Ctrl+C to stop the server.
ECHO.
powershell -NoProfile -Command ^
"$listener = [System.Net.Sockets.TcpListener]::new('0.0.0.0', %PORT%);" ^
"$listener.Start();" ^
"$client = $listener.AcceptTcpClient();" ^
"$stream = $client.GetStream();" ^
"$reader = [System.IO.StreamReader]::new($stream);" ^
"$data = $reader.ReadLine();" ^
"Write-Host ('Received data: ' + $data);" ^
"$client.Close();" ^
"$listener.Stop();"
ECHO.
ECHO --- Server has shut down ---
How the PowerShell Method Works (A Step-by-Step Breakdown)
The one-liner is a sequence of .NET networking commands:
$listener = ... TcpListener::new('0.0.0.0', %PORT%): Creates a newTcpListenerobject that will listen on all network interfaces (0.0.0.0) on the specified port.$listener.Start(): Starts the listener.$client = $listener.AcceptTcpClient(): This is the blocking part of the command. The script will pause here and wait until a client connects.$stream = $client.GetStream(): Gets the network stream for reading and writing data.$reader = ... StreamReader::new(...): Creates an object to make reading text from the stream easier.$data = $reader.ReadLine(): Reads a single line of text sent by the client.Write-Host ('...'): Prints the received data to the PowerShell console.$client.Close(); $listener.Stop();: Properly closes the connection and stops the listener.
Common Pitfalls and How to Solve Them
CRITICAL: The Windows Firewall
This is the number one reason a listener will fail to accept connections from other machines. The Windows Defender Firewall will, by default, block incoming connections to applications it doesn't recognize.
Solution: The first time you run this script, Windows will likely show a Security Alert prompt. You must click "Allow access". This will automatically create a firewall rule for the script. For a truly automated deployment, you would need a separate command (netsh advfirewall ...) to create this rule beforehand.
Problem: The Script "Hangs" or Blocks
The script seems to freeze after printing "Listening on port...".
Solution: This is not a bug; this is the correct and expected behavior of a server. The $listener.AcceptTcpClient() part is a "blocking call" that is designed to wait indefinitely for a connection. To stop the script, you must either connect a client to it or press Ctrl+C.
Practical Example: A Simple Remote Log Receiver
This example consists of two scripts: a "server" that listens for messages and a "client" that sends a message to it.
The Listener Script (LogServer.bat)
@ECHO OFF
SET "PORT=9999"
:Loop
ECHO [%time%] Waiting for a log message on port %PORT%...
powershell -C "$l=[System.Net.Sockets.TcpListener]::new('0.0.0.0',%PORT%);$l.Start();$c=$l.AcceptTcpClient();$s=$c.GetStream();$r=[System.IO.StreamReader]::new($s);$d=$r.ReadLine();$l.Stop();[System.IO.File]::AppendAllText('C:\Logs\remote.log', [System.DateTime]::Now + ' - ' + $d + [System.Environment]::NewLine)"
GOTO :Loop
This is a more advanced version that runs in an infinite loop and appends any received messages to a file.
The Client Script (SendLog.bat)
@ECHO OFF
SET "ServerIP=127.0.0.1"
SET "ServerPort=9999"
SET "Message=CRITICAL: The backup process failed."
ECHO Sending message: "%Message%"
powershell -C "$c=New-Object System.Net.Sockets.TcpClient('%ServerIP%',%ServerPort%);$s=$c.GetStream();$w=[System.IO.StreamWriter]::new($s);$w.WriteLine('%Message%');$w.Flush();$c.Close()"
Conclusion
While batch scripting cannot listen for TCP connections on its own, it is a perfect launcher for a PowerShell one-liner that can.
Key takeaways:
- Do not attempt to create a TCP listener in pure batch. It is not possible.
- The PowerShell
[System.Net.Sockets.TcpListener]class is the modern, built-in, and recommended method. - You must allow the script through the Windows Firewall the first time it runs.
- Understand that a listener script is supposed to wait (block) until a connection is made.