学习C#
2005-04-03 16:44
197 查看
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
*******************************************************************
获取本机名和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
相关文章推荐
- C# 学习笔记(3)
- c#学习之基础篇(动态打开,显示,保存,另存为 图片)[待续]
- C#学习第七天
- C#语言学习--基础部分(四) --关系运算符,判断语句
- 学习C#第一天
- C#学习之旅2
- c#中odp.net 4.0利用odac操作oracle数据库学习(五)
- C# 事件学习
- C#学习笔记 委托
- 【C#】1.3 WPF应用程序学习要点
- C#学习之关于lock
- C#学习——CLR异常处理原理
- OSG学习:C#调用非托管C++方法——C++/CLI
- 专业开发: MSIL语言学习笔记 - C#
- 数据库学习四:c#调用存储过程
- C#学习 属性的访问器
- (原创)c#学习笔记09--定义类06--接口和抽象类
- c#学习5——C#中的继承(inherit)
- C#学习之路
- C#设计模式学习笔记-单例模式