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; private IPAddress _address;\ private int _port; private IPEndPoint _endPoint; private bool _disposed; 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); // Get the response // Buffer to store the response bytes bytes = new byte[1024]; // Display the response int bytesRead = ns.Read(bytes, 0, bytes.Length); string serverResponse = Encoding.ASCII.GetString(bytes, 0, bytesRead);\ Trace.WriteLine("Server said: " + serverResponse); } } catch (SocketException se) { Trace.WriteLine("There was an error talking to the server: " + se.ToString()); } finally { Dispose(); } } #region IDisposable Members public void Dispose() { Dispose(true); ...
Get C# 3.0 Cookbook, 3rd Edition 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.