Skip to content
CShift0.32

TcpListener

Struct · namespace System.Net · Since 0.30

struct TcpListener : IDisposable

A TCP server: listens on a port and accepts the connections of clients, each a TcpConnection.

using System;
using System.Net;
using var listener = try TcpListener.Start("127.0.0.1", 8080);
while (true)
{
using var client = try listener.Accept();
var request = new uint8[4096];
int got = try client.Read(request, 0, request.Length);
try client.WriteText("HTTP/1.1 200 OK\r\nContent-Length: 6\r\nConnection: close\r\n\r\nHello\n");
}

TcpListener.Pending and TcpConnection.WaitForData wait with a time limit: one thread can serve several connections and do other work in between. Like a FileStream, a listener is a struct around a handle of the operating system: copies of it share the handle, and TcpListener.Stop of one stops all of them; keep one owner. The zero value (TcpListener { }) is a stopped listener. Only IPv4.

Name Description
Start Listens on port of address: "127.0.0.1" (or "localhost") accepts the connections from this computer only, "0.0.0.0" those from every network.
static NetError<TcpListener> Start(StringSlice address, int port)

Listens on port of address: "127.0.0.1" (or "localhost") accepts the connections from this computer only, "0.0.0.0" those from every network. Port 0 takes a free port; TcpListener.Port says which one.

Errors

Panics when port is not in 0..65535.

Name Description
IsListening Whether it listens (it is not stopped).
Port The port it listens on: the one given to TcpListener.Start, or the free one that the system chose for port 0.
Pending Waits up to milliseconds for a client to connect (0: does not wait; -1: waits as long as it takes).
Accept Takes the next connection of a client; waits for one if none is TcpListener.Pending.
Stop Stops listening; the connections that it accepted stay open.
Dispose Stops listening (TcpListener.Stop); using calls it.
bool IsListening()

Whether it listens (it is not stopped).

int Port()

The port it listens on: the one given to TcpListener.Start, or the free one that the system chose for port 0.

bool Pending(int milliseconds)

Waits up to milliseconds for a client to connect (0: does not wait; -1: waits as long as it takes).

Returns whether a connection is waiting: TcpListener.Accept then takes it without waiting.

NetError<TcpConnection> Accept()

Takes the next connection of a client; waits for one if none is TcpListener.Pending.

Errors

void Stop()

Stops listening; the connections that it accepted stay open. Stopping again does nothing.

void Dispose()

Stops listening (TcpListener.Stop); using calls it.