まずはじめに、簡単な例として Daytime (RFC 867) client プログラムを コンソールアプリケーションとして作ってみる。Client の仕事は、
using System;
using System.Net.Sockets;
class myTcpTest
{
public static int Main(string [] args)
{
if( args.Length != 1 )
{
Console.WriteLine( "Give the hostname of the daytime server" );
return 1;
}
Int32 port = 13;
TcpClient myclient = new TcpClient( args[0], port );
NetworkStream mystream = myclient.GetStream();
Byte [] recvdata = new Byte [256];
String recvstr = String.Empty;
Int32 nbytes = mystream.Read(recvdata, 0, recvdata.Length);
recvstr = System.Text.Encoding.ASCII.GetString(recvdata, 0, nbytes);
Console.Write( recvstr );
myclient.Close();
return 0;
}
}
Byte 列と、String の変換が必要なので、多少ゴタゴタしているが、 基本的に難しい部分は無い。
エラーを捕捉するのも、try - catch で行えばよいので、面倒では 無い。Socket エラーを捉えるように変更してみよう。
using System;
using System.Net.Sockets;
class myTcpTest
{
public static int Main(string [] args)
{
if( args.Length != 1 )
{
Console.WriteLine( "Give the hostname of the daytime server" );
return 1;
}
Int32 port = 13;
try
{
TcpClient myclient = new TcpClient( args[0], port );
NetworkStream mystream = myclient.GetStream();
Byte [] recvdata = new Byte [256];
String recvstr = String.Empty;
Int32 nbytes = mystream.Read(recvdata, 0, recvdata.Length);
recvstr = System.Text.Encoding.ASCII.GetString(recvdata, 0, nbytes);
Console.Write( recvstr );
myclient.Close();
}
catch( SocketException e )
{
Console.WriteLine( "SocketException: {0}", e );
}
return 0;
}
}