学习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 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值