Advertisement
Guest User

Untitled

a guest
May 10th, 2012
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.24 KB | None | 0 0
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Threading;
  6.  
  7. namespace Server
  8. {
  9.     public class SynchronousSocketListener
  10.     {
  11.  
  12.         public static string data = null;
  13.  
  14.         public static void StartListening()
  15.         {
  16.             // Data buffer for incoming data.
  17.             byte[] bytes = new Byte[1024];
  18.  
  19.             IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
  20.             IPEndPoint localEndPoint = new IPEndPoint(ipHostInfo.AddressList[0], 11010);
  21.  
  22.             Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  23.  
  24.             try
  25.             {
  26.                 listener.Bind(localEndPoint);
  27.                 listener.Listen(10);
  28.  
  29.                 while (true)
  30.                 {
  31.                     Console.WriteLine("Waiting for a connection...");
  32.                     Socket handler = listener.Accept();
  33.                     data = null;
  34.  
  35.                     while (true)
  36.                     {
  37.                         bytes = new byte[1024];
  38.                         int bytesRec = handler.Receive(bytes);
  39.                         data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
  40.                         if (data.IndexOf("<EOF>") > -1)
  41.                         {
  42.                             break;
  43.                         }
  44.                     }
  45.  
  46.                     Console.WriteLine("Text received : {0}", data);
  47.  
  48.                     byte[] msg = Encoding.ASCII.GetBytes(data);
  49.  
  50.                     foreach (var address in ipHostInfo.AddressList)
  51.                     {
  52.                         IPEndPoint ep = new IPEndPoint(address,11010);
  53.                         handler.SendTo(msg, ep);
  54.                     }
  55.                        
  56.  
  57.                     handler.Shutdown(SocketShutdown.Both);
  58.                     handler.Close();
  59.                 }
  60.  
  61.             }
  62.             catch (Exception e)
  63.             {
  64.                 Console.WriteLine(e.ToString());
  65.             }
  66.  
  67.             Console.WriteLine("\nPress ENTER to continue...");
  68.             Console.Read();
  69.  
  70.         }
  71.  
  72.         public static int Main(String[] args)
  73.         {
  74.             StartListening();
  75.             return 0;
  76.         }
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement