16 Chapter 2: Basic Sockets
■
TcpListener
Class
Socket Class
WinSock 2.0 Implementation
TcpClient
Class
UdpClient
Class
.NET
Framework
Classes
Underlying
Implementation
Figure 2.1: Relationship of Socket classes.
In 2002 Microsoft released the standardized API framework known as .NET, which
provides a unified class library across all of the programming languages Microsoft offers.
Among the features of the library are higher level classes that hide much of the implemen-
tation detail and simplify many programming tasks. However, abstraction can sometimes
hide some of the flexibility and power of a lower level interface. In order to allow access
to the underlying sockets interface, Microsoft implemented a .NET Socket class, which is
a wrapper around the WinSock socket functions and has most of the versatility (and com-
plexity) of sockets interface exposed. Then three higher-level socket classes, TcpClient,
TcpListener, and UdpClient, were implemented by using the .NET Socket wrapper class.
In fact, these classes have a protected property that is an instance of the Socket class they
are using. Pictorially this can be represented as shown in Figure 2.1.
Why is this important to know? First, to clarify what we mean when we refer to a
“socket.” The word socket has come to mean many different things in network program-
ming, from an API to a class name or instance. In general when we refer to an uppercase
“Socket” we mean the .NET class, while a lowercase “socket” refers to a socket instance
using any of the .NET socket classes.
Second, the underlying implementation occasionally becomes apparent to the .NET
programmer. Sometimes the Socket class needs to be utilized to take advantage of
advanced functionality. Some components of the underlying WinSock implementation
are also still visible, such as the use of WinSock error codes, which are available via
the ErrorCode property of SocketException and can be used to determine exactly what
type of error has occurred. The WinSock error codes are discussed in more detail in the
Appendix.
2.3 TCP Sockets
The .NET framework provides two classes specifically for TCP: TcpClient and TcpListener.
These classes provide a higher level abstraction of the Socket class, but as we will see