Csharp/CSharp Tutorial/Network/TcpListener — различия между версиями

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

Текущая версия на 12:20, 26 мая 2010

Asynch Network Server

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
        class ClientHandler
        {
            private byte[] buffer = new byte[256];
            private Socket socket;
            private NetworkStream networkStream;
            private AsyncCallback callbackRead;
            private AsyncCallback callbackWrite;
            public ClientHandler(Socket socketForClient)
            {
                socket = socketForClient;
                networkStream = new NetworkStream(socketForClient);
                callbackRead = new AsyncCallback(this.OnReadComplete);
                callbackWrite = new AsyncCallback(this.OnWriteComplete);
            }
            public void StartRead()
            {
                networkStream.BeginRead(buffer, 0, buffer.Length,callbackRead, null);
            }
            private void OnReadComplete(IAsyncResult ar)
            {
                int bytesRead = networkStream.EndRead(ar);
                if (bytesRead > 0)
                {
                    string s = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead);
                    Console.Write(s);
                    networkStream.BeginWrite(buffer, 0, bytesRead, callbackWrite, null);
                }
                else
                {
                    networkStream.Close();
                    socket.Close();
                    networkStream = null;
                    socket = null;
                }
            }
            private void OnWriteComplete(IAsyncResult ar)
            {
                networkStream.EndWrite(ar);
                networkStream.BeginRead(buffer, 0, buffer.Length,callbackRead, null);
            }
        }
    public class AsynchNetworkServer
    {
        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();
                ClientHandler handler =new ClientHandler(socketForClient);
                handler.StartRead();
            }
        }
    }

Create a Socket server from TcpListener

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;
    }
  }
}

Create BinaryWriter and BinaryReader from TcpListener

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
class MainClass
{
    public static void Main() 
    {
        TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8000);
        Console.WriteLine("About to initialize port.");
        listener.Start();
        Console.WriteLine("Listening for a connection...");
            
        try 
        {
            using (TcpClient client = listener.AcceptTcpClient())
            {
                Console.WriteLine("Connection accepted.");
                NetworkStream stream = client.GetStream();
                using (BinaryWriter w = new BinaryWriter(stream))
                {
                }
                using (BinaryReader r = new BinaryReader(stream))
                {
                }
            }
        } 
        catch (Exception ex) 
        {
            Console.WriteLine(ex.ToString());
        }
        finally
        {
            listener.Stop();
            Console.WriteLine("Listener stopped.");
        }
   }
}

Listening for sockets

using System;
using System.Net;
using System.Text;
using System.Net.Sockets;
class MainClass
{
  [STAThread]
  static void Main(string[] args)
  {
    int PortNumber = 10000;
    TcpListener MyListener = new TcpListener(IPAddress.Parse("127.0.0.1"), PortNumber);
    MyListener.Start();
    Console.WriteLine("Waiting For Connection");
    TcpClient MyClient = MyListener.AcceptTcpClient();
    Console.WriteLine("Connection Accepted");
    NetworkStream MyNetStream = MyClient.GetStream();
    String Response = "accepted";
    Byte[] SendTheseBytes = Encoding.ASCII.GetBytes(Response);
    MyNetStream.Write(SendTheseBytes, 0, SendTheseBytes.Length);
    MyClient.Close();
    MyListener.Stop();
  }
}

TcpListener Sample

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MainClass
{
   public static void Main()
   {
      int receivedDataLength;
      byte[] data = new byte[1024];
      TcpListener socket = new TcpListener(9999);
      socket.Start();
      TcpClient client = socket.AcceptTcpClient();
      NetworkStream ns = client.GetStream();
      string welcome = "Welcome";
      data = Encoding.ASCII.GetBytes(welcome);
      ns.Write(data, 0, data.Length);
      while(true)
      {
         data = new byte[1024];
         receivedDataLength = ns.Read(data, 0, data.Length);
         Console.WriteLine(Encoding.ASCII.GetString(data, 0, receivedDataLength));
         ns.Write(data, 0, receivedDataLength);
      }
      ns.Close();
      client.Close();
      socket.Stop();
   }
}

Time Server

using System.Net.Sockets;
using System.IO;
using System;
using System.Threading;
public class TimeServer {
    public static void Main() {
        TcpListener server = new TcpListener(55555);
        server.Start();
        Console.WriteLine("Waiting for connections");
        while (true) {
            Socket client = server.AcceptSocket();
            Console.WriteLine("New connection detected on " + client.Handle);
            ClientHandler ch = new ClientHandler(client);
        }
    }
}
class ClientHandler {
    private Socket client;
    public ClientHandler(Socket client) {
        this.client = client;
        Thread clientThread = new Thread(new ThreadStart(ClientSession));
        clientThread.Start();
    }
    public void ClientSession() {
        NetworkStream netStream = new NetworkStream(client);
        BinaryWriter timeOut = new BinaryWriter(netStream);
        String time = DateTime.Now.ToString();
        timeOut.Write(time);
        timeOut.Close();
        netStream.Close();
        client.Close();
    }
}

Use NetworkStream to write to a client

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;
    }
  }
}

Use TcpListener to create a Tcp server

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
class MainClass
{
    public static void Main() 
    {
        TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8000);
        Console.WriteLine("About to initialize port.");
        listener.Start();
        Console.WriteLine("Listening for a connection...");
            
        try 
        {
            using (TcpClient client = listener.AcceptTcpClient())
            {
                Console.WriteLine("Connection accepted.");
                NetworkStream stream = client.GetStream();
                using (BinaryWriter w = new BinaryWriter(stream))
                {
                }
                using (BinaryReader r = new BinaryReader(stream))
                {
                }
            }
        } 
        catch (Exception ex) 
        {
            Console.WriteLine(ex.ToString());
        }
        finally
        {
            listener.Stop();
            Console.WriteLine("Listener stopped.");
        }
   }
}