Csharp/CSharp Tutorial/Network/Socket Server

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

Accepting a socket connection (simple file-server)

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.IO.rupression;
using System.Net;
using System.Net.Mail;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
public class MainClass
{
    private static void HandleRequest(object state)
    {
        using (Socket client = (Socket)state)
        using (NetworkStream stream = new NetworkStream(client))
        using (StreamReader reader = new StreamReader(stream))
        using (StreamWriter writer = new StreamWriter(stream))
        {
            string fileName = reader.ReadLine();
            writer.Write(File.ReadAllText(fileName));
        }
    }
    public static void Main()
    {
        using (Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp))
        {
            s.Bind(new IPEndPoint(IPAddress.Loopback, 9999));
            s.Listen(3);
            Socket client = s.Accept();
            ThreadPool.QueueUserWorkItem(HandleRequest, client);
        }
    }
}

GUI based Tcp Server

/*
Quote from 
C# Network Programming
# Paperback: 656 pages
# Publisher: Sybex (November 26, 2002)
# Language: English
# ISBN-10: 0782141765
# ISBN-13: 978-0782141764
*/
using System;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

public class AsyncTcpSrvr : Form
{
   private TextBox conStatus;
   private ListBox results;
   private byte[] data = new byte[1024];
   private int size = 1024;
   private Socket server;

   public AsyncTcpSrvr()
   {
      Text = "Asynchronous TCP Server";
      Size = new Size(400, 380);
      results = new ListBox();
      results.Parent = this;
      results.Location = new Point(10, 65);
      results.Size = new Size(350, 20 * Font.Height);
      Label label1 = new Label();
      label1.Parent = this;
      label1.Text = "Text received from client:";
      label1.AutoSize = true;
      label1.Location = new Point(10, 45);
      Label label2 = new Label();
      label2.Parent = this;
      label2.Text = "Connection Status:";
      label2.AutoSize = true;
      label2.Location = new Point(10, 330);
      conStatus = new TextBox();
      conStatus.Parent = this;
      conStatus.Text = "Waiting for client...";
      conStatus.Size = new Size(200, 2 * Font.Height);
      conStatus.Location = new Point(110, 325);
      Button stopServer = new Button();
      stopServer.Parent = this;
      stopServer.Text = "Stop Server";
      stopServer.Location = new Point(260,32);
      stopServer.Size = new Size(7 * Font.Height, 2 * Font.Height);
      stopServer.Click += new EventHandler(ButtonStopOnClick);
      server = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream, ProtocolType.Tcp);
      IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
      server.Bind(iep);
      server.Listen(5);
      server.BeginAccept(new AsyncCallback(AcceptConn), server);
   }
   void ButtonStopOnClick(object obj, EventArgs ea)
   {
      Close();
   }
   void AcceptConn(IAsyncResult iar)
   {
      Socket oldserver = (Socket)iar.AsyncState;
      Socket client = oldserver.EndAccept(iar);
      conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();
      string stringData = "Welcome to my server";
      byte[] message1 = Encoding.ASCII.GetBytes(stringData);
      client.BeginSend(message1, 0, message1.Length, SocketFlags.None,
                  new AsyncCallback(SendData), client);
   }
   void SendData(IAsyncResult iar)
   {
      Socket client = (Socket)iar.AsyncState;
      int sent = client.EndSend(iar);
      client.BeginReceive(data, 0, size, SocketFlags.None,
                  new AsyncCallback(ReceiveData), client);
   }
   void ReceiveData(IAsyncResult iar)
   {
      Socket client = (Socket)iar.AsyncState;
      int recv = client.EndReceive(iar);
      if (recv == 0)
      {
         client.Close();
         conStatus.Text = "Waiting for client...";
         server.BeginAccept(new AsyncCallback(AcceptConn), server);
         return;
      }
      string receivedData = Encoding.ASCII.GetString(data, 0, recv);
      results.Items.Add(receivedData);
      byte[] message2 = Encoding.ASCII.GetBytes(receivedData);
      client.BeginSend(message2, 0, message2.Length, SocketFlags.None,
                   new AsyncCallback(SendData), client);
   }
   public static void Main()
   {
      Application.Run(new AsyncTcpSrvr());
   }
}

Listen for Socket Request in Thread

using System;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
public class MainClass {
    static void ListenForRequests() {
        int CONNECT_QUEUE_LENGTH = 4;
        
        Socket listenSock = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
        listenSock.Bind( new IPEndPoint(IPAddress.Any,9999) );
        listenSock.Listen( CONNECT_QUEUE_LENGTH );
        while( true ) {
            using( Socket newConnection = listenSock.Accept() ) {
                // Send the data.
                byte[] msg = Encoding.UTF8.GetBytes( "Hello World!" );
                newConnection.Send( msg, SocketFlags.None );
            }
        }
    }
    static void Main() {
        // Start the listening thread.
        Thread listener = new Thread(new ThreadStart(ListenForRequests) );
        listener.IsBackground = true;
        listener.Start();
        Console.WriteLine( "Press <enter> to quit" );
        Console.ReadLine();
    }
}

Simple Tcp server: receive data from a client

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MainClass
{
   public static void Main()
   {
      IPEndPoint ip = new IPEndPoint(IPAddress.Any,9999);
      Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
      socket.Bind(ip);
      socket.Listen(10);
      Console.WriteLine("Waiting for a client...");
      Socket client = socket.Accept();
      IPEndPoint clientep =(IPEndPoint)client.RemoteEndPoint;
      Console.WriteLine("Connected with {0} at port {1}",clientep.Address, clientep.Port);
      
      string welcome = "Welcome";
      byte[] data = new byte[1024];
      data = Encoding.ASCII.GetBytes(welcome);
      client.Send(data, data.Length,SocketFlags.None);
      while(true)
      {
         data = new byte[1024];
         int receivedDataLength = client.Receive(data);
         Console.WriteLine(Encoding.ASCII.GetString(data, 0, receivedDataLength));
         client.Send(data, receivedDataLength, SocketFlags.None);
      }
      Console.WriteLine("Disconnected from {0}",clientep.Address);
      client.Close();
      socket.Close();
   }
}

Tcp server based on Thread

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class MainClass
{
   public static void Main()
   {
      TcpListener client = new TcpListener(9050);
      client.Start();
      Console.WriteLine("Waiting for clients...");
      while(true)
      {
         while (!client.Pending())
         {
            Thread.Sleep(10000);
         }
         ConnectionThread newconnection = new ConnectionThread(client);
      }
   }
}
class ConnectionThread
{
   TcpListener threadListener;
   public ConnectionThread(TcpListener lis){
      threadListener = lis;
      Thread newthread = new Thread(new ThreadStart(HandleConnection));
      newthread.Start();
   }
   
   public void HandleConnection()
   {
      byte[] data = new byte[1024];
      TcpClient client = threadListener.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];
         int recv = ns.Read(data, 0, data.Length);
         if (recv == 0)
            break;
         ns.Write(data, 0, recv);
      }
      ns.Close();
      client.Close();
   }
}

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

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MainClass
{
   public static void Main()
   {
      string data;
      IPEndPoint ip = new IPEndPoint(IPAddress.Any, 9999);
      Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
      socket.Bind(ip);
      socket.Listen(10);
      Socket client = socket.Accept();
      IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
      Console.WriteLine("Connected with {0} at port {1}",newclient.Address, newclient.Port);
      NetworkStream ns = new NetworkStream(client);
      StreamReader sr = new StreamReader(ns);
      StreamWriter sw = new StreamWriter(ns);
      string welcome = "Welcome";
      sw.WriteLine(welcome);
      sw.Flush();
      while(true)
      {
         data = sr.ReadLine();
         Console.WriteLine(data);
         sw.WriteLine(data);
         sw.Flush();
      }
      Console.WriteLine("Disconnected from {0}", newclient.Address);
      sw.Close();
      sr.Close();
      ns.Close(); 
   }
}

ThreadPool based Tcp server

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class MainClass 
{
   public static void Main()
   {
      TcpListener client = new TcpListener(9050);
      client.Start();
      Console.WriteLine("Waiting for clients...");
      while(true)
      {
         while (!client.Pending())
         {
            Thread.Sleep(1000);
         }
         ConnectionThread newconnection = new ConnectionThread(client);
      }
   }
}
class ConnectionThread
{
   public TcpListener threadListener;
   public ConnectionThread(TcpListener lis){
     threadListener = lis;
     ThreadPool.QueueUserWorkItem(new WaitCallback(HandleConnection));
   }
   
   public void HandleConnection(object state)
   {
      int recv;
      byte[] data = new byte[1024];
      TcpClient client = threadListener.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];
         recv = ns.Read(data, 0, data.Length);
         ns.Write(data, 0, recv);
      }
      ns.Close();
      client.Close();
   }
}

Use background thread to deal with the Server socket

using System;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
public class MainClass {
    private const int CONNECT_QUEUE_LENGTH = 4;
    static void ListenForRequests() {
        Socket listenSock = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
        listenSock.Bind( new IPEndPoint(IPAddress.Any, 9999) );
        listenSock.Listen( CONNECT_QUEUE_LENGTH );
        while( true ) {
            Socket newConnection = listenSock.Accept();
            byte[] msg = Encoding.UTF8.GetBytes( "Hello!" );
            newConnection.BeginSend( msg,0, msg.Length, SocketFlags.None, null, null );
        }
    }
    static void Main() {
        Thread listener = new Thread(new ThreadStart(ListenForRequests) );
        listener.IsBackground = true;
        listener.Start();
        Console.WriteLine( "Press <enter> to quit" );
        Console.ReadLine();
    }
}