Home
Browse all 647 examples
Download all 647 examples
Download sample chapters
Reviews
Errata
Acknowledgments
Links on .NET
Paradoxal Press
Buy directly from Paradoxal Press at $33.99 (Save 43%)
Category: Programming
Level: Beginner to seasoned
900 pages
ISBN-10 097661322-0
ISBN-13 978-097661322-0
$59.99 USA
$79.99 CANADA
|
Listing 17-5 extracted from chapter Input/Output and streams
Listing 17-4< > Listing 17-6
This listing can be compiled with the command line: csc.exe /out:Server.exe /target:exe Example_17_5_to_rename_Server.cs Errors: 0 Warnings: 0
Example_17_5_to_rename_Server.cs
using System;
using System.Net.Sockets;
using System.Net;
using System.IO;
class ProgServeur {
static readonly ushort port = 50000;
static void Main() {
IPAddress ipAddress = new IPAddress( new byte[] { 127, 0, 0, 1 } );
TcpListener tcpListener = new TcpListener( ipAddress , port );
tcpListener.Start();
// Each loop = send a file to a client.
while(true) {
try {
Console.WriteLine( "Waiting for a client..." );
// 'AcceptTcpClient()' is a blocking call. The thread
// continue its course only when a client is connected.
TcpClient tcpClient = tcpListener.AcceptTcpClient();
Console.WriteLine( "Client connected." );
ProcessClientRequest( tcpClient.GetStream() );
Console.WriteLine( "Client disconnected." );
}
catch( Exception e ) {
Console.WriteLine( e.Message );
}
}
}
static void ProcessClientRequest( NetworkStream networkStream ) {
// Stream used to send data.
StreamWriter streamWriter = new StreamWriter( networkStream );
// Stream used to read the file.
StreamReader streamReader = new StreamReader( @"C:/Text/File.txt" );
// For each line of the file: send it to the client.
string sTmp = streamReader.ReadLine();
try {
while(sTmp != null ) {
Console.WriteLine( "Sending: {0}" , sTmp );
streamWriter.WriteLine( sTmp );
streamWriter.Flush();
sTmp = streamReader.ReadLine();
}
}
finally {
// Close streams.
streamReader.Close();
streamWriter.Close();
networkStream.Close();
}
}
}
Copyright Patrick Smacchia 2006 2007
|