このようなことでうまくいくはずですが、大量の例外的な条件の処理や、サーバーの正常なシャットダウンなどの小さなことが欠けていると確信しています。
static void Main( string[] args )
{
string localMachineName = Dns.GetHostName() ;
IPHostEntry localMachineInfo = Dns.GetHostEntry( localMachineName ) ;
IPAddress localMachineAddress = localMachineInfo.AddressList[0] ;
IPEndPoint localEndPoint = new IPEndPoint( localMachineAddress , PORT_NUMBER ) ;
using ( Socket server = new Socket( localEndPoint.AddressFamily , SocketType.Stream , ProtocolType.Tcp ) )
{
server.Bind( localEndPoint ) ;
server.Listen( PENDING_CONNECTIONS_QUEUE_LENGTH ) ;
while ( true )
{
using ( Socket connection = server.Accept() )
using ( NetworkStream connectionStream = new NetworkStream( connection , FileAccess.Read , false ) )
using ( TextReader connectionReader = new StreamReader( connectionStream , Encoding.UTF8 ) )
{
IPEndPoint remoteEndpoint = (IPEndPoint) connection.RemoteEndPoint ;
string line ;
while ( null != (line=connectionReader.ReadLine()) )
{
line = line.Trim() ;
Console.WriteLine( "Client says: {0}" , line ) ;
if ( string.Equals( "exit" , line , StringComparison.InvariantCultureIgnoreCase ) ) break ;
if ( string.Equals( "quit" , line , StringComparison.InvariantCultureIgnoreCase ) ) break ;
if ( string.Equals( "goodbye" , line , StringComparison.InvariantCultureIgnoreCase ) ) break ;
if ( string.Equals( "good-bye" , line , StringComparison.InvariantCultureIgnoreCase ) ) break ;
}
connection.Shutdown( SocketShutdown.Both ) ;
connection.Close() ;
}
}
}
}
ストリームをバッファリングする場合は、NetworkStream
インスタンスを次のように装飾しますBufferedStream
。
using ( Socket connection = server.Accept() )
using ( Stream connectionStream = new NetworkStream( connection , FileAccess.Read , false ) )
using ( TextReader connectionReader = new StreamReader( new BufferedStream( connectionStream ) , Encoding.UTF8 ) )
{
IPEndPoint remoteEndpoint = (IPEndPoint) connection.RemoteEndPoint ;
string line ;
while ( null != (line=connectionReader.ReadLine()) )
{
line = line.Trim() ;
Console.WriteLine( "Client says: {0}" , line ) ;
if ( string.Equals( "exit" , line , StringComparison.InvariantCultureIgnoreCase ) ) break ;
if ( string.Equals( "quit" , line , StringComparison.InvariantCultureIgnoreCase ) ) break ;
if ( string.Equals( "goodbye" , line , StringComparison.InvariantCultureIgnoreCase ) ) break ;
if ( string.Equals( "good-bye" , line , StringComparison.InvariantCultureIgnoreCase ) ) break ;
}
connection.Shutdown( SocketShutdown.Both ) ;
connection.Close() ;
}