/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// NStrCli.cs -- Acts as a client program to demonstrate the use of
// the NetworkStream class.
//
// Compile this program with the following command line.
// C:>csc NStrCli.cs
//
// To use this program with the companion server program, first start
// the server, then connect to it using the client program (this program)
// in a separate console window.
// As you enter lines from the client, they will appear in the server
// console window. To end the session, press <Enter> on a blank line.
//
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace nsStreams
{
public class NStrCli
{
static public void Main ()
{
IPAddress hostadd = Dns.Resolve("localhost").AddressList[0];
Console.WriteLine ("Host is " + hostadd.ToString());
IPEndPoint EPhost = new IPEndPoint(hostadd, 2048);
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp );
string str = "Hello, World!";
byte [] b;
StringToByte (out b, str);
s.Connect (EPhost);
NetworkStream strm = new NetworkStream (s, FileAccess.ReadWrite);
if (!s.Connected)
{
Console.WriteLine ("Unable to connect to host");
return;
}
strm.Write (b, 0, b.Length);
while (b[0] != 4)
{
string text = Console.ReadLine();
if (text.Length == 0)
{
b[0] = 4;
strm.Write (b, 0, 1);
break;
}
StringToByte (out b, text);
strm.Write (b, 0, text.Length);
}
strm.Close ();
s.Close ();
}
//
// Convert a buffer of type byte to a string
static string ByteToString (byte [] b, int start)
{
string str = "";
for (int x = start; x < b.Length; ++x)
{
str += (char) b [x];
}
return (str);
}
//
// Convert a buffer of type string to byte
static void StringToByte (out byte [] b, string str)
{
b = new byte [str.Length];
for (int x = 0; x < str.Length; ++x)
{
b[x] = (byte) str [x];
}
}
}
}
|