Csharp/C Sharp/Network/Udp Client — различия между версиями

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

Текущая версия на 11:46, 26 мая 2010

Bad Udp Client

/*
C# Network Programming 
by Richard Blum
Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class BadUdpClient
{
   public static void Main()
   {
      byte[] data = new byte[30];
      string input, stringData;
      IPEndPoint ipep = new IPEndPoint(
                      IPAddress.Parse("127.0.0.1"), 9050);
      Socket server = new Socket(AddressFamily.InterNetwork,
                     SocketType.Dgram, ProtocolType.Udp);
      string welcome = "Hello, are you there?";
      data = Encoding.ASCII.GetBytes(welcome);
      server.SendTo(data, data.Length, SocketFlags.None, ipep);
      IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
      EndPoint tmpRemote = (EndPoint)sender;
      data = new byte[30];
      int recv = server.ReceiveFrom(data, ref tmpRemote);
      Console.WriteLine("Message received from {0}:", tmpRemote.ToString());
      Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

      while(true)
      {
         input = Console.ReadLine();
         if (input == "exit")
            break;
         server.SendTo(Encoding.ASCII.GetBytes(input), tmpRemote);
         data = new byte[30];
         recv = server.ReceiveFrom(data, ref tmpRemote);
         stringData = Encoding.ASCII.GetString(data, 0, recv);
         Console.WriteLine(stringData);
      }
      Console.WriteLine("Stopping client");
      server.Close();
   }
}


Best Udp Client

/*
C# Network Programming 
by Richard Blum
Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class BestUdpClient
{
   private static byte[] data = new byte[1024];
   private static IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
   private static EndPoint Remote = (EndPoint)sender;
   private static int size = 30;
   private static int AdvSndRcvData(Socket s, byte[] message, EndPoint rmtdevice)
   {
      int recv = 0;
      int retry = 0;
      while (true)
      {
         Console.WriteLine("Attempt #{0}", retry);
         try
         {
            s.SendTo(message, message.Length, SocketFlags.None, rmtdevice);
            data = new byte[size];
            recv = s.ReceiveFrom(data, ref Remote);
         } catch (SocketException e)
         {
            if (e.ErrorCode == 10054)
               recv = 0;
            else if (e.ErrorCode == 10040)
            {
               Console.WriteLine("Error receiving packet");
               size += 10;
               recv = 0;
            }
         }
         if (recv > 0)
         {
            return recv;
         } else
         {
            retry++;
            if (retry > 4)
            {
               return 0;
            }
         }
      }
   }
   public static void Main()
   {
      string input, stringData;
      int recv;
      IPEndPoint ipep = new IPEndPoint(
                      IPAddress.Parse("127.0.0.1"), 9050);
      Socket server = new Socket(AddressFamily.InterNetwork,
                     SocketType.Dgram, ProtocolType.Udp);
      int sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
      Console.WriteLine("Default timeout: {0}", sockopt);
      server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000);
      sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
      Console.WriteLine("New timeout: {0}", sockopt);
 
      string welcome = "Hello, are you there?";
      data = Encoding.ASCII.GetBytes(welcome);
      recv = AdvSndRcvData(server, data, ipep);
      if (recv > 0)
      {
         stringData = Encoding.ASCII.GetString(data, 0, recv);
         Console.WriteLine(stringData);
      } else
      {
         Console.WriteLine("Unable to communicate with remote host");
         return;
      }
      while(true)
      {
         input = Console.ReadLine();
         if (input == "exit")
            break;
         recv = AdvSndRcvData(server, Encoding.ASCII.GetBytes(input), ipep);
         if (recv > 0)
         {
            stringData = Encoding.ASCII.GetString(data, 0, recv);
            Console.WriteLine(stringData);
         } else
            Console.WriteLine("Did not receive an answer");
      }
      Console.WriteLine("Stopping client");
      server.Close();
   }
}


Better Udp Client

/*
C# Network Programming 
by Richard Blum
Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class BetterdUdpClient
{
   public static void Main()
   {
      byte[] data = new byte[30];
      string input, stringData;
      IPEndPoint ipep = new IPEndPoint(
                      IPAddress.Parse("127.0.0.1"), 9050);
      Socket server = new Socket(AddressFamily.InterNetwork,
                     SocketType.Dgram, ProtocolType.Udp);
      string welcome = "Hello, are you there?";
      data = Encoding.ASCII.GetBytes(welcome);
      server.SendTo(data, data.Length, SocketFlags.None, ipep);
      IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
      EndPoint tmpRemote = (EndPoint)sender;
      data = new byte[30];
      int recv = server.ReceiveFrom(data, ref tmpRemote);
      Console.WriteLine("Message received from {0}:", tmpRemote.ToString());
      Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

      int i = 30;
      while(true)
      {
         input = Console.ReadLine();
         if (input == "exit")
            break;
         server.SendTo(Encoding.ASCII.GetBytes(input), tmpRemote);
         data = new byte[i];
         try
         {
            recv = server.ReceiveFrom(data, ref tmpRemote);
            stringData = Encoding.ASCII.GetString(data, 0, recv);
            Console.WriteLine(stringData);
         } catch (SocketException)
         {
            Console.WriteLine("WARNING: data lost, retry message.");
            i += 10;
         }
      }
      Console.WriteLine("Stopping client");
      server.Close();
   }
}


Binary Udp Client

/*
C# Network Programming 
by Richard Blum
Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class BinaryUdpClient
{
   public static void Main()
   {
      byte[] data = new byte[1024];
      string stringData;
      UdpClient server = new UdpClient("127.0.0.1", 9050);
      IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
      string welcome = "Hello, are you there?";
      data = Encoding.ASCII.GetBytes(welcome);
      server.Send(data, data.Length);
      data = new byte[1024];
      data = server.Receive(ref sender);
      Console.WriteLine("Message received from {0}:", sender.ToString());
      stringData = Encoding.ASCII.GetString(data, 0, data.Length);
      Console.WriteLine(stringData);
   
      int test1 = 45;
      double test2 = 3.14159;
      int test3 = -1234567890;
      bool test4 = false;
      string test5 = "This is a test.";
      byte[] data1 = BitConverter.GetBytes(test1);
      server.Send(data1, data1.Length);
      byte[] data2 = BitConverter.GetBytes(test2);
      server.Send(data2, data2.Length);
      byte[] data3 = BitConverter.GetBytes(test3);
      server.Send(data3, data3.Length);
      byte[] data4 = BitConverter.GetBytes(test4);
      server.Send(data4, data4.Length);
      byte[] data5 = Encoding.ASCII.GetBytes(test5);
      server.Send(data5, data5.Length);
      Console.WriteLine("Stopping client");
      server.Close();
   }
}


Exception Udp Client

/*
C# Network Programming 
by Richard Blum
Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class ExceptionUdpClient
{
   public static void Main()
   {
      byte[] data = new byte[1024];
      string input, stringData;
      int recv;
      IPEndPoint ipep = new IPEndPoint(
                      IPAddress.Parse("127.0.0.1"), 9050);
      Socket server = new Socket(AddressFamily.InterNetwork,
                     SocketType.Dgram, ProtocolType.Udp);
      int sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
      Console.WriteLine("Default timeout: {0}", sockopt);
      server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000);
      sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
      Console.WriteLine("New timeout: {0}", sockopt);
      string welcome = "Hello, are you there?";
      data = Encoding.ASCII.GetBytes(welcome);
      server.SendTo(data, data.Length, SocketFlags.None, ipep);
      IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
      EndPoint Remote = (EndPoint)sender;
      data = new byte[1024];
      try
      {
         recv = server.ReceiveFrom(data, ref Remote);
         Console.WriteLine("Message received from {0}:", Remote.ToString());
         Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
      } catch (SocketException)
      {
         Console.WriteLine("Problem communicating with remote server");
         return;
      }
      while(true)
      {
         input = Console.ReadLine();
         if (input == "exit")
            break;
         server.SendTo(Encoding.ASCII.GetBytes(input), ipep);
         data = new byte[1024];
         try
         {
            recv = server.ReceiveFrom(data, ref Remote);
            stringData = Encoding.ASCII.GetString(data, 0, recv);
            Console.WriteLine(stringData);
         } catch (SocketException)
         {
            Console.WriteLine("Error receiving message");
         }
      }
      Console.WriteLine("Stopping client");
      server.Close();
   }
}


Odd Udp Client

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class OddUdpClient
{
   public static void Main()
   {
      byte[] data = new byte[1024];
      string input, stringData;
      IPEndPoint ipep = new IPEndPoint(
                      IPAddress.Parse("127.0.0.1"), 9050);
      Socket server = new Socket(AddressFamily.InterNetwork,
                     SocketType.Dgram, ProtocolType.Udp);
      server.Connect(ipep);
      string welcome = "Hello, are you there?";
      data = Encoding.ASCII.GetBytes(welcome);
      server.Send(data);
      data = new byte[1024];
      int recv = server.Receive(data);
      Console.WriteLine("Message received from {0}:", ipep.ToString());
      Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

      while(true)
      {
         input = Console.ReadLine();
         if (input == "exit")
            break;
         server.Send(Encoding.ASCII.GetBytes(input));
         data = new byte[1024];
         recv = server.Receive(data);
         stringData = Encoding.ASCII.GetString(data, 0, recv);
         Console.WriteLine(stringData);
      }
      Console.WriteLine("Stopping client");
      server.Close();
   }
}


Retry Udp Client

/*
C# Network Programming 
by Richard Blum
Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class RetryUdpClient
{
   private byte[] data = new byte[1024];
   private static IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
   private static EndPoint Remote = (EndPoint)sender;
   private int SndRcvData(Socket s, byte[] message, EndPoint rmtdevice)
   {
      int recv;
      int retry = 0;
      while (true)
      {
         Console.WriteLine("Attempt #{0}", retry);
         try
         {
            s.SendTo(message, message.Length, SocketFlags.None, rmtdevice);
            data = new byte[1024];
            recv = s.ReceiveFrom(data, ref Remote);
         } catch (SocketException)
         {
            recv = 0;
         }
         if (recv > 0)
         {
            return recv;
         } else
         {
            retry++;
            if (retry > 4)
            {
               return 0;
            }
         }
      }
   }
   public RetryUdpClient()
   {
      string input, stringData;
      int recv;
      IPEndPoint ipep = new IPEndPoint(
                      IPAddress.Parse("127.0.0.1"), 9050);
      Socket server = new Socket(AddressFamily.InterNetwork,
                     SocketType.Dgram, ProtocolType.Udp);
      int sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
      Console.WriteLine("Default timeout: {0}", sockopt);
      server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000);
      sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
      Console.WriteLine("New timeout: {0}", sockopt);
      string welcome = "Hello, are you there?";
      data = Encoding.ASCII.GetBytes(welcome);
      recv = SndRcvData(server, data, ipep);
      if (recv > 0)
      {
         stringData = Encoding.ASCII.GetString(data, 0, recv);
         Console.WriteLine(stringData);
      } else
      {
         Console.WriteLine("Unable to communicate with remote host");
         return;
      }
      while(true)
      {
         input = Console.ReadLine();
         if (input == "exit")
            break;
         recv = SndRcvData(server, Encoding.ASCII.GetBytes(input), ipep);
         if (recv > 0)
         {
            stringData = Encoding.ASCII.GetString(data, 0, recv);
            Console.WriteLine(stringData);
         } else
            Console.WriteLine("Did not receive an answer");
      }
      Console.WriteLine("Stopping client");
      server.Close();
   }
   public static void Main()
   {
      RetryUdpClient ruc = new RetryUdpClient();
   }
}


Simple Udp Client

/*
C# Network Programming 
by Richard Blum
Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SimpleUdpClient
{
   public static void Main()
   {
      byte[] data = new byte[1024];
      string input, stringData;
      IPEndPoint ipep = new IPEndPoint(
                      IPAddress.Parse("127.0.0.1"), 9050);
      Socket server = new Socket(AddressFamily.InterNetwork,
                     SocketType.Dgram, ProtocolType.Udp);

      string welcome = "Hello, are you there?";
      data = Encoding.ASCII.GetBytes(welcome);
      server.SendTo(data, data.Length, SocketFlags.None, ipep);
      IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
      EndPoint Remote = (EndPoint)sender;
      data = new byte[1024];
      int recv = server.ReceiveFrom(data, ref Remote);
      Console.WriteLine("Message received from {0}:", Remote.ToString());
      Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
      while(true)
      {
         input = Console.ReadLine();
         if (input == "exit")
            break;
         server.SendTo(Encoding.ASCII.GetBytes(input), Remote);
         data = new byte[1024];
         recv = server.ReceiveFrom(data, ref Remote);
         stringData = Encoding.ASCII.GetString(data, 0, recv);
         Console.WriteLine(stringData);
      }
      Console.WriteLine("Stopping client");
      server.Close();
   }
}


Test Udp Client

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class TestUdpClient
{
   public static void Main()
   {
      byte[] data = new byte[1024];
      IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
      Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);
      string welcome = "Hello, are you there?";
      data = Encoding.ASCII.GetBytes(welcome);
      server.SendTo(data, data.Length, SocketFlags.None, ipep);
      IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
      EndPoint tmpRemote = (EndPoint)sender;
      data = new byte[1024];
      int recv = server.ReceiveFrom(data, ref tmpRemote);
      Console.WriteLine("Message received from {0}:", tmpRemote.ToString());
      Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

      server.SendTo(Encoding.ASCII.GetBytes("message 1"), tmpRemote);
      server.SendTo(Encoding.ASCII.GetBytes("message 2"), tmpRemote);
      server.SendTo(Encoding.ASCII.GetBytes("message 3"), tmpRemote);
      server.SendTo(Encoding.ASCII.GetBytes("message 4"), tmpRemote);
      server.SendTo(Encoding.ASCII.GetBytes("message 5"), tmpRemote);
      Console.WriteLine("Stopping client");
      server.Close();
   }
}


Time out Udp Client

/*
C# Network Programming 
by Richard Blum
Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class TimeoutUdpClient
{
   public static void Main()
   {
      byte[] data = new byte[1024];
      string input, stringData;
      int recv;
      IPEndPoint ipep = new IPEndPoint(
                      IPAddress.Parse("127.0.0.1"), 9050);
      Socket server = new Socket(AddressFamily.InterNetwork,
                     SocketType.Dgram, ProtocolType.Udp);
      int sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
      Console.WriteLine("Default timeout: {0}", sockopt);
      server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000);
      sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
      Console.WriteLine("New timeout: {0}", sockopt);
      string welcome = "Hello, are you there?";
      data = Encoding.ASCII.GetBytes(welcome);
      server.SendTo(data, data.Length, SocketFlags.None, ipep);
      IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
      EndPoint tmpRemote = (EndPoint)sender;
      data = new byte[1024];
      recv = server.ReceiveFrom(data, ref tmpRemote);
      Console.WriteLine("Message received from {0}:", tmpRemote.ToString());
      Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
      while(true)
      {
         input = Console.ReadLine();
         if (input == "exit")
            break;
         server.SendTo(Encoding.ASCII.GetBytes(input), tmpRemote);
         data = new byte[1024];
         recv = server.ReceiveFrom(data, ref tmpRemote);
         stringData = Encoding.ASCII.GetString(data, 0, recv);
         Console.WriteLine(stringData);
      }
      Console.WriteLine("Stopping client");
      server.Close();
   }
}


Udp Client Multi Receive

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UdpClientMultiRecv
{
   public static void Main()
   {
      UdpClient sock = new UdpClient(9050);
      Console.WriteLine("Ready to receive...");
      sock.JoinMulticastGroup(IPAddress.Parse("192.100.0.1"), 50);
      IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0);
      byte[] data = sock.Receive(ref iep);
      string stringData = Encoding.ASCII.GetString(data, 0, data.Length);
      Console.WriteLine("received: {0}  from: {1}", stringData, iep.ToString());
      sock.Close();
   }
}


Udp Client Multi Send

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UdpClientMultiSend
{
   public static void Main()
   {
      UdpClient sock = new UdpClient();
      IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.100.0.1"), 9050);
      byte[] data = Encoding.ASCII.GetBytes("This is a test message");
      sock.Send(data, data.Length, iep);
      sock.Close();
   }
}


Udp Client Sample

/*
C# Network Programming 
by Richard Blum
Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UdpClientSample
{
   public static void Main()
   {
      byte[] data = new byte[1024];
      string input, stringData;
      UdpClient server = new UdpClient("127.0.0.1", 9050);
      IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
      string welcome = "Hello, are you there?";
      data = Encoding.ASCII.GetBytes(welcome);
      server.Send(data, data.Length);
      data = server.Receive(ref sender);
      Console.WriteLine("Message received from {0}:", sender.ToString());
      stringData = Encoding.ASCII.GetString(data, 0, data.Length);
      Console.WriteLine(stringData);
      while(true)
      {
         input = Console.ReadLine();
         if (input == "exit")
            break;
       
         server.Send(Encoding.ASCII.GetBytes(input), input.Length);
         data = server.Receive(ref sender);
         stringData = Encoding.ASCII.GetString(data, 0, data.Length);
         Console.WriteLine(stringData);
      }
      Console.WriteLine("Stopping client");
      server.Close();
   }
}