網頁

2015年11月25日 星期三

C# 簡單的 TCP Socket 測試

Last Update: 2016/04/24 02:46+08



Intro

兩種作法
System.Net.Sockets.TcpListener & System.Net.Sockets.TcpClient
System.Net.Sockets.Socket
但事實上差不多, 沒什麼特別需求可以用第一種節省點Code
Socket只能為 Actively 或 Passtively 不能同時為兩種
看倌們可以自己試試, 要求連線後成功後是不能等候連線的



Content


TcpListener & TcpClient
static AutoResetEvent are = new AutoResetEvent(false);
public static void Main(string[] args)
{
 //Client background worker
 System.Threading.ThreadPool.QueueUserWorkItem(delegate
 {
  using (var client = new TcpClient("192.168.153.1", 5002))
  {
   are.WaitOne();
   using (var stm = client.GetStream())
   {
    var buffer = Encoding.UTF8.GetBytes("hello world!");
    stm.Write(buffer, 0, buffer.Length);
   }
  }
 });



 //Server background worker
 System.Threading.ThreadPool.QueueUserWorkItem(delegate
 {
  var listener = new TcpListener(IPAddress.Parse("192.168.153.1"), 5002);
  try
  {
   listener.Start();
   var handler = listener.AcceptTcpClient();
   byte[] buffer = new byte[1518];
   using (var stm = handler.GetStream())
   {
    var dataSize = stm.Read(buffer, 0, buffer.Length);
    Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, dataSize));
   }

  }
  finally { listener.Stop(); }

 });

 while (Console.ReadKey().Key != ConsoleKey.Escape)
 {
  are.Set();//任意鍵往下一步走
 }
}
在接入連線的部份有分AcceptTcpClient和AcceptSocket
用來傳回不同類別給你處理資料



Socket
static AutoResetEvent are = new AutoResetEvent(false);

public static void Main(string[] args)
{
 
 are.Reset();

 //Client background worker
 System.Threading.ThreadPool.QueueUserWorkItem(delegate
 {
  var activelySkt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  try
  {
   activelySkt.Bind(new IPEndPoint(IPAddress.Parse("192.168.153.1"), 5001));
   are.WaitOne();
   activelySkt.Connect(new IPEndPoint(IPAddress.Parse("192.168.153.1"), 5002));
   are.WaitOne();
   activelySkt.Send(Encoding.UTF8.GetBytes("hello world"));
   are.WaitOne();
  }
  finally
  {
   activelySkt.Disconnect(false);
   activelySkt.Close();
  }

 });



 //Server background worker
 System.Threading.ThreadPool.QueueUserWorkItem(delegate
 {
  var passtivelySkt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  try
  {
   passtivelySkt.Bind(new IPEndPoint(IPAddress.Parse("192.168.153.1"), 5002));
   passtivelySkt.Listen(100);

   while (true)
   {
    var handler = passtivelySkt.Accept();
    byte[] buffer = new byte[1518];
    var dataSize = handler.Receive(buffer);
    Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, dataSize));
   }
  }
  finally
  {
   passtivelySkt.Disconnect(false);
   passtivelySkt.Close();
  }
 });


 while (Console.ReadKey().Key != ConsoleKey.Escape)
 {
  are.Set();//任意鍵往下一步走
 }

}

沒有留言:

張貼留言