
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Writing a TCP Client
|
883
See Also
See the “IPAddress Class,” “TcpListener Class,” and “TcpClient Class” topics in the
MSDN documentation.
16.2 Writing a TCP Client
Problem
You want to interact with a TCP-based server.
Solution
Use the MyTcpClient class shown in Example 16-2 to connect to and converse with a
TCP-based server by passing the address and port of the server to talk to, using the
System.Net.TcpClient class. This example will talk to the server from Recipe 16.1.
Example 16-2. MyTcpClient class
class MyTcpClient
{
private TcpClient _client = null;
private IPAddress _address;
private int _port;
private IPEndPoint _endPoint = null;
public MyTcpClient(IPAddress address, int port)
{
_address = address;
_port = port;
_endPoint = new IPEndPoint(_address, _port);
}
public void ConnectToServer(string msg)
{
try
{
_client = new TcpClient( );
_client.Connect(_endPoint);
// Get the bytes to send for the message.
byte[] bytes = Encoding.ASCII.GetBytes(msg);
// Get the stream to talk to the server on.
using (NetworkStream ns = _client.GetStream( ))
{
// Send message.
Trace.WriteLine("Sending message to server: " + msg);
ns.Write(bytes, 0, bytes.Length);