
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
878
|
Chapter 16: Networking
Solution
Use the MyTcpServer class created here to listen on a TCP-based endpoint for requests
arriving on a given port:
class MyTcpServer
{
#region Private Members
private TcpListener _listener = null;
private IPAddress _address;
private int _port;
private bool _listening = false;
#endregion
#region CTORs
public MyTcpServer(IPAddress address, int port)
{
_port = port;
_address = address;
}
#endregion // CTORs
The TCPServer class has two properties:
•
Address, an IPAddress
• Port, an int
These return the current address and port on which the server is listening and the lis-
tening state:
#region Properties
public IPAddress Address
{
get { return _address; }
}
public int Port
{
get { return _port; }
}
public bool Listening
{
get { return _listening; }
}
#endregion
The Listen method tells the MyTcpServer class to start listening on the specified
address and port combination. You create and start a
TcpListener, then call its
AcceptTcpClient method to wait for a client request to arrive. Once the client con-
nects, a request is sent to the thread pool to service the client and that runs the
ProcessClient method.