Using TCP, UDP, and Sockets

The System.Net.Sockets namespace includes types that provide protocol-level support for TCP and UDP. These types are built on the underlying Socket type, which is itself directly accessible for transport-level access to the network.

Two classes provide the TCP support: TcpListener and TcpClient. TcpListener listens for incoming connections, creating Socket instances that respond to the connection request. TcpClient connects to a remote host, hiding the details of the underlying socket in a Stream-derived type that allows stream I/O over the network.

A class called UdpClient provides the UDP support. UdpClient serves as both a client and a listener, and includes multicast support, allowing individual datagrams to be sent and received as byte arrays.

Both the TCP and the UDP classes help to access the underlying network socket (represented by the Socket class). The Socket class is a thin wrapper over the native Windows sockets functionality and is the lowest level of networking accessible to managed code.

The following example is a simple implementation of the Quote of the Day (qotd) protocol, as defined by the IETF in RFC 865. It demonstrates the use of a TCP listener to accept incoming requests and the use of the lower-level Socket type to fulfill the request:

// QOTDListener.cs // Run QOTDListener.exe to service incoming QOTD requests using System; using System.Net; using System.Net.Sockets; using System.Text; class QOTDListener { static string[] quotes = ...

Get C# in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.