Csharp/CSharp Tutorial/Network/NetworkStream

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Create a NetworkStream from a Socket

using System;
using System.IO;
using System.Net.Sockets ;
class MainClass
{
  public static void Main() 
  {
    TcpListener tcpl = new TcpListener(9999);
    tcpl.Start();
    for (;;)
    {
      Socket newSocket = tcpl.AcceptSocket();
      if (newSocket.Connected)
      {
        NetworkStream ns = new NetworkStream(newSocket);
        byte[] buf = {1,2,3,4,5,6,7,8,9};
        ns.Write(buf, 0, 9);
        ns.Flush();
        ns.Close();
      }
      newSocket.Close();
      break;
    }
  }
}

Network Streaming Client

using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
   public class Client
   {
      static public void Main( string[] Args )
      {
         TcpClient socketForServer = new TcpClient( "localHost", 65000 );
         NetworkStream networkStream = socketForServer.GetStream();
         System.IO.StreamReader streamReader = new System.IO.StreamReader( networkStream );
         string outputString;
         do{
           outputString = streamReader.ReadLine();
           if ( outputString != null )
           {
              Console.WriteLine( outputString );
           }
         }while ( outputString != null );
         networkStream.Close();
      }
   }

Network Streaming Server

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
   public class NetworkIOServer
   {
      public static void Main()
      {
         IPAddress localAddr = IPAddress.Parse( "127.0.0.1" );
         TcpListener tcpListener = new TcpListener( localAddr, 65000 );
         tcpListener.Start();
         for ( ; ; )
         {
            Socket socketForClient = tcpListener.AcceptSocket();
            SendFileToClient( socketForClient );
            socketForClient.Close();
            break;
         }
      }
      static void SendFileToClient(Socket socketForClient )
      {
         NetworkStream networkStream = new NetworkStream( socketForClient );
         System.IO.StreamWriter streamWriter = new System.IO.StreamWriter( networkStream );
         System.IO.StreamReader streamReader = new System.IO.StreamReader("myTest.txt" );
         string theString;
         do
         {
            theString = streamReader.ReadLine();
            if ( theString != null )
            {
               Console.WriteLine("Sending {0}", theString );
               streamWriter.WriteLine( theString );
               streamWriter.Flush();
            }
         }
         while ( theString != null );
         streamReader.Close();
         networkStream.Close();
         streamWriter.Close();
      }
   }

NetworkStream TcpClient

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MainClass
{
   public static void Main()
   {
      IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
      Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
      try
      {
         server.Connect(ip);
      } catch (SocketException e){
         Console.WriteLine(e.ToString());
         return;
      }
      NetworkStream ns = new NetworkStream(server);
      if (ns.CanRead){
         byte[] data = new byte[1024];
         int receivedDataLength = ns.Read(data, 0, data.Length);
         string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
         Console.WriteLine(stringData);
      }else{
         Console.WriteLine("Error: Can"t read from this socket");
      }
      ns.Close();
      server.Shutdown(SocketShutdown.Both);
      server.Close();
   }
}

Tcp client: Use StreamReader and StreamWriter to read and write to a server

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MainClass
{
   public static void Main()
   {
      string data;
      string input;
      IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
      Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
      try
      {
         server.Connect(ip);
      } catch (SocketException e)
      {
         Console.WriteLine(e.ToString());
         return;
      }
      NetworkStream ns = new NetworkStream(server);
      StreamReader sr = new StreamReader(ns);
      StreamWriter sw = new StreamWriter(ns);
      data = sr.ReadLine();
      Console.WriteLine(data);
      while(true)
      {
         input = Console.ReadLine();
         sw.WriteLine(input);
         sw.Flush();
         data = sr.ReadLine();
         Console.WriteLine(data);
      }
      sr.Close();
      sw.Close();
      ns.Close();
      server.Shutdown(SocketShutdown.Both);
      server.Close();
   }
}

Use NetworkStream to read and write to a server

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MainClass
{
   public static void Main()
   {
      IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
      Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
      try
      {
         server.Connect(ip);
      } catch (SocketException e){
         Console.WriteLine(e.ToString());
         return;
      }
      NetworkStream ns = new NetworkStream(server);
      while(true)
      {
         byte[] data = new byte[1024];
         string input = Console.ReadLine();
         if (ns.CanWrite){
            ns.Write(Encoding.ASCII.GetBytes(input), 0, input.Length);
            ns.Flush();
         }
         int receivedDataLength = ns.Read(data, 0, data.Length);
         string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
         Console.WriteLine(stringData);
      }
      ns.Close();
      server.Shutdown(SocketShutdown.Both);
      server.Close();
   }
}