學習C#

TCP/IP 網絡應用
*******************************************************************
獲取本機名和IP地址
*******************************************************************
using System;
using System.Net;

public class IPTest
{
   public static int Main()
   {
      string strHostName;
      strHostName = Dns.GetHostName();
      Console.WriteLine("本機名: " + strHostName);
  
      IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
      IPAddress [] addr = ipEntry.AddressList;
      string [] str = ipEntry.Aliases;
      for(int i=0; i<addr.Length; ++i)
      {
         Console.WriteLine("IP地址[{0}] : {1}", i, addr[i].ToString());
         Console.WriteLine("地址類型[{0}] : {1}", i, addr[i].AddressFamily.ToString());
      }
      return 0;
   }
}

*********************************************************************
Tcp網絡時間服務應用
*********************************************************************
//服務器端:提供時間服務
using System;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Text;

public class DateServer
{
   private TcpListener myListener;
   private int port = 4554;

   public DateServer()
   {
      try
      {
         myListener = new TcpListener(port);
         myListener.Start();
         Console.WriteLine("服務器端就緒 - 正在接受鏈接...");
         Thread th = new Thread(new ThreadStart(StartListen));
         th.Start();
      }
      catch(Exception e)
      {
         Console.WriteLine("啓動監聽時發生異常:" + e.ToString());
      }
   }

   public static void Main (string [] argv)
   {
      DateServer dts = new DateServer();
   }

   public void StartListen()
   {
      while(true)
      {
  Socket mySocket = myListener.AcceptSocket();
         if(mySocket.Connected)
         {
            Console.WriteLine("Client Connected!!");
            Btye[] receive = new Byte[64];
            int i = mySocket.Receive(receive, receive.Length, 0);
            string rece = System.Text.Encoding.ASCII.GetString(reveive);
            ConSole.WriteLine(rece);
            if(string.Compare(rece, "ReqTime" == 0)
            {
                DateTime new = DateTime.Now;
                String strDateLine = "服務器時間" + now.ToString();
                Byte[] byteDateLine = Encoding.Uncode.GetBytes(strDateLine.ToCharArray());
                mySocket.Send(byteDateLine, byteDateLine.Length, 0);
            }
         }
      }
   }
}

//客戶端: 請求時間服務
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
public class DateClient
{
   private TcpClient tcpc;
   private string name;
   private int port = 4554;
   private bool readData = false;
  
   public DateClient(string name)
   {
      tryagain:
         this.name = name;
      try
      {
         tcpc = new TcpClient("localhost", port);
         NetworkStream nts = tcpc.GetStream();
        
         if(nts.CanWrite)
         {
            string sender = "ReqTime";
            Byte[] sends = Encoding.Unicode.GetBytes(sender.ToCharArray());
            nts.Write(sends, 0, sends.Length);
            nts.Flush();
         }
        
         while(!readData && nts.CanRead)
         {
            if(nts.DataAvailable)
            {
               byte[] rcd = new byte[128];
               int i = nts.Read(rcd, 0, 128);
               string ree = Encoding.Unicode.GetString(rcd);
               Console.WriteLine(ree);
               readData = true;
            }
         }
      }
      catch(Exception e)
      {
         Console.WriteLine("無法鏈接到服務器 " + e.ToString());
         Console.Write("在嘗試一次?[y/n]:");
         char check = (char)Console.Read();
         if(check == 'y' || check == 'Y')
            goto tryagain;
      }

    public static void Main(string[] argv)
    {
        if(argv.Length <= 0)
        {
           Console.WriteLine("使用方法: DataClient <yourname>");
           Console.Write("是否要輸入服務器名稱[y/n]?");
           char check = (char) Console.Read();
           if(check == 'y' || check == 'Y')
           {
              Console.Write("請輸入服務器名稱: ");
              string newname = Console.ReadLine();
              DateClient dc = new DateClient(newname);
              Console.WriteLien("斷開鏈接!");
              Console.ReadLine();
           }
        }
        else
        {
           DateClient dc = new DateClient(argv[0]);
           Console.WriteLine("斷開鏈接!");
           Console.ReadLine();
        }
    }  
}

****************************************************************************************
Udp 組播網絡時間服務應用
****************************************************************************************
//時間服務器端
using System;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Text;

class UdpServer
{
   private static int port = 2001;
   public static void Main()
   {
      UdpClient uc = new UdpClient();
      IPAddress MultiCastip = IPAddress.Parse("225.3.12.45");
      uc.Connect(MultiCastip, port);
      while(true)
      {
         Thread.Sleep(1000);
         DateTime now = DateTime.Now;
         String strDateTime = now.ToString();
         Console.WriteLine("服務器時間: " + strDateTime);
         Byte[] byteDateTime = EnCoding.Uncode.GetBytes(strDateTime.ToCharArray());
         uc.Send(byteDateTime, byteDateTime.Length);
      }
}

//時間服務客戶端
using System;
using System.Net.Sockets;
using System.Net;
using System.Text;

class UdpClients
{
   private static int port = 2001;
   public static void Main()
   {
      UdpClient uc = new UdpClient(port);
      IPAddress MultiCastip = IPAddress.Parse("225.3.12.45");
      uc.JoinMulticastGroup(MultipCastip);
      IPEndPoint ipEnd = new IPEndPoint(MultiCastip, port);
      Console.WriteLine("準備接受時間...");
  
      while(true)
      {
         Byte[] rxDateTimeBuf = uc.Receive(ref ipEnd);
         string strDateTime = Encoding.Unicode.GetString(rxDateTimeBuf);
         Console.WriteLine("客戶端接收的時間" + strDateTime);
      }
   }
}

多線程編程
***********************************************************************************
工作線程
***********************************************************************************
//Windows 方式
VOID ReadTime(VOID);

HANDLE hThread;
DWORD  ThreadID;
hThread = CreateThread(NULL, 0, (LPTHREAD_START_RUNTINE)ReaTime, NULL, 0, &ThreadID);

VOID ReadTime(VOID)
{
   char str[50];
   SYSTEMTIME st;
   while(1)
   {
      GetSystemTime(&st);
      sprintf(str, "%u:%u:%u", st.wHour, st.wMinute, st.wSecond);
      SetDlgItemText(hwndDlg, IDE_TIME, str);
      Sleep(1000);
   }
}

//C# 方式
public class Foo
{
   public VOID ReadTime(VOID);
};

VOID Foo::ReadTime(VOID)
{
   char str[50];
   SYSTEMTIME st;
   while(1)
   {
      DateTime now = DateTime.Now;
      string strDateLine = now.ToShortDateString() + " " + now.ToLongTimeString();
      Thread.Sleep(1000);
   }
}

public class Simple
{
   public static int Main(string[] args)
   {
      Console.WriteLine("Thread Simple Sample");
      Foo oFoo = new Foo();
      Thread oThread = new Thread(new ThreadStart(oFoo.ReadTime));
      oThread.Start();
      return 0;
   }
}

//Win32 Runtime    //Visual C#
CreateThread[CreateThread(&Method)] Combination of Thread and ThreadStart[new Thread(newThreadStart(&oFoo::Method))]
TerminateThread    Thread.Abort
SuspendThread    Thread.Suspend
ResumeThread    Thread.Resume
Sleep     Thread.Sleep
ExitThread    ExitThread
GetCurrentThread   Thread.CurrentThread
SetThreadPriority   Thread.Priority
WaitForSingleObject   on the thread handle Thread.Join
No equivalent    Thread.Name
No equivalent    Thread.ApartmentState
No equivalent    Thread.IsBackground

//應用配置和組件
***********************************************************************************
依據符號包含和排除代碼
***********************************************************************************
using System;
public class SquareSample
{
   public void CalcSquare(int nSideLength, out int nSquared)
   {
      nSquared = nSideLength * nSideLength;
   }
   public int CalcSquare(int nSideLength)
   {
      return nSideLength * nSideLength;
   }
}

class SquareApp
{
   public static void Main()
   {
      SquareSample sq = new SquareSample();
      int nSquared = 0;
     
      #if CALC_W_OUT_PARAM
      sq.CalcSquare(20, out, nSquared);
      #else     
      nSquared = sq.CalcSquared(15);
      #endif
     
      Console.WriteLine(nSquared.ToString());
   }
}

#define RELEASE
#define DEMOVERSION

#if DEBUG
#undef DEMOVERSION
#endif

using System;
class Demo
{
   public static void Main()
   {
      #if DEBUG
      Console.WriteLine("Debug version");
      #endif RELEASE && !DEMOVERSION
      Console.WriteLine("Full release version");
      #else
      Console.WriteLine("Demo version");
      #endif
   }
}

***********************************************************************************
引發編譯警告和錯誤信息
***********************************************************************************
#define DEBUG
#define RELEASE
#defien DEMOVERSION

#if DEMOVERSION && !DEBUG
#warning You are building a demo version
#endif

using System;
class Demo
{
   public static void Main()
   {
      Console.WriteLine("Demo Application");
   }
}

***********************************************************************************
條件屬性
***********************************************************************************
#define DEBUG

using System;
class Info
{
   [conditional("DEBUG")]
   public static void Trace(string strMessage)
   {
      Console.WriteLine(strMessage);
   }
  
   [Conditional("DEBUG")]
   public static void TraceX(string strFormat, params object[] list)
   {
      Console.WriteLine(strFormat, list);
   }
}

class TestConditional
{
   public static void Main()
   {
      Info.Trace("Cool");
      Info.TraceX("{0} {1} {2}", "C", "U", 2001);
   }
}

***********************************************************************************
設計組件
*********************************************************************************** 
csc File.cs
csc /target:library File.cs

using CSComponent;
using VBComponent;
../csc /reference:cscomponent.dll /reference:vbcomponet.dll /target:winexe form1.cs 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章