一、同步方式:1.服务器端 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( "客户端与服务器链接成功!" ); ProcessClientRequest( tcpClient.GetStream() ); Console.WriteLine( "客户端与服务器断开链接!" ); } 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(); } } }
2.客户端 Client.cs
using System; using System.Net.Sockets; using System.IO; class ProgClient { static readonly string host = "localhost"; static readonly ushort port = 50000; static void Main() { TcpClient tcpClient; try { // Invoking the ‘TcpClient’ constructor raises an exception // if it can’t connect to the server. tcpClient = new TcpClient( host , port ); Console.WriteLine("连接到的服务器IP地址:{0},端口号:{1}",host,port); NetworkStream networkStream = tcpClient.GetStream(); StreamReader streamReader = new StreamReader( networkStream ); try { // Each loop = a line is fetched from the server. string sTmp = streamReader.ReadLine(); while( sTmp != null ) { Console.WriteLine( "Receiving: {0}" , sTmp ); sTmp = streamReader.ReadLine(); } } finally { // Close stream. streamReader.Close(); networkStream.Close(); Console.WriteLine( "断开的服务器IP地址:{0},端口:{1}", host, port); Console.Read(); } } catch( Exception e ) { Console.WriteLine( e.Message ); return; } } }
二、异步方式 1.服务器端 Server.cs
using System; using System.Net.Sockets; using System.Net; using System.IO; using System.Text; 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(); while(true) { try { Console.WriteLine( "Main:Waiting for a client..." ); TcpClient tcpClient = tcpListener.AcceptTcpClient(); Console.WriteLine( "Main:Client connected." ); ClientRequestProcessing clientRequestProcessing = new ClientRequestProcessing( tcpClient.GetStream() ); clientRequestProcessing.Go(); } catch( Exception e ) { Console.WriteLine( e.Message ); } } } } // An instance of this class is created for each client. class ClientRequestProcessing { static readonly int bufferSize = 512; private byte [] m_Buffer; private NetworkStream m_NetworkStream; private AsyncCallback m_CallbackRead; private AsyncCallback m_CallbackWrite; // The constructor initializes : // - m_NetworkStream: stream to communicate with the client. // - m_CallbackRead : callback procedure for read. // - m_CallbackWrite: callback procedure for write. // - m_Buffer : used both for reading and writing data. public ClientRequestProcessing( NetworkStream networkStream ) { m_NetworkStream = networkStream; m_CallbackRead = new AsyncCallback( this.OnReadDone ); m_CallbackWrite = new AsyncCallback( this.OnWriteDone ); m_Buffer = new byte[ bufferSize ]; } public void Go() { m_NetworkStream.BeginRead( m_Buffer, 0 , m_Buffer.Length , m_CallbackRead , null ); } // This callback procedure is called when an asynchronous read // triggered by a call to ‘BeginRead()’ terminates. private void OnReadDone( IAsyncResult asyncResult ) { int nBytes = m_NetworkStream.EndRead(asyncResult ); // Send back the received string to the client. if( nBytes > 0 ){ string s = Encoding.ASCII.GetString( m_Buffer , 0 , nBytes ); Console.Write( "Async:{0} bytes received from client: {1}" , nBytes, s ); m_NetworkStream.BeginWrite( m_Buffer, 0 , nBytes , m_CallbackWrite , null ); } // If the client didn’t send anything, the we discard him. else{ Console.WriteLine( "Async:Client request processed." ); m_NetworkStream.Close(); m_NetworkStream = null; } } // This callback procedure is called when an asynchronous write // triggered by a call to ‘BeginWrite()’ terminates. private void OnWriteDone( IAsyncResult asyncResult ) { m_NetworkStream.EndWrite( asyncResult ); Console.WriteLine( "Async:Write done." ); m_NetworkStream.BeginRead( m_Buffer, 0 , m_Buffer.Length , m_CallbackRead , null ); } }
using System; using System.Net.Sockets; using System.IO; class ProgClient { static readonly string host = "localhost"; static readonly ushort port = 50000; static void Main() { TcpClient tcpClient; try{ // Invoking the ‘TcpClient’ constructor raises an exception // if it can’t connect to the server. tcpClient = new TcpClient(host,port); Console.WriteLine("Connection established with {0}:{1}",host,port); // Initialize the stream to communicate with the server // available for sending and receiving data. NetworkStream networkStream = tcpClient.GetStream(); StreamWriter streamWriter =new StreamWriter( networkStream ); StreamReader streamReader =new StreamReader( networkStream ); try { string sSend = "Hi from the client!"; string sReceived; for(int i=0;i<3;i++) { // Send data to the server. Console.WriteLine( "Client -> Server :" + sSend ); streamWriter.WriteLine( sSend ); streamWriter.Flush(); // Receiving data from the server. sReceived = streamReader.ReadLine(); Console.WriteLine( "Server -> Client :" + sReceived ); } } finally{ streamWriter.Close(); streamReader.Close(); networkStream.Close(); } } catch(Exception e) { Console.WriteLine( e.Message ); return; } } }