Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- namespace Server
- {
- public class SynchronousSocketListener
- {
- public static string data = null;
- public static void StartListening()
- {
- // Data buffer for incoming data.
- byte[] bytes = new Byte[1024];
- IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
- IPEndPoint localEndPoint = new IPEndPoint(ipHostInfo.AddressList[0], 11010);
- Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- try
- {
- listener.Bind(localEndPoint);
- listener.Listen(10);
- while (true)
- {
- Console.WriteLine("Waiting for a connection...");
- Socket handler = listener.Accept();
- data = null;
- while (true)
- {
- bytes = new byte[1024];
- int bytesRec = handler.Receive(bytes);
- data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
- if (data.IndexOf("<EOF>") > -1)
- {
- break;
- }
- }
- Console.WriteLine("Text received : {0}", data);
- byte[] msg = Encoding.ASCII.GetBytes(data);
- foreach (var address in ipHostInfo.AddressList)
- {
- IPEndPoint ep = new IPEndPoint(address,11010);
- handler.SendTo(msg, ep);
- }
- handler.Shutdown(SocketShutdown.Both);
- handler.Close();
- }
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- Console.WriteLine("\nPress ENTER to continue...");
- Console.Read();
- }
- public static int Main(String[] args)
- {
- StartListening();
- return 0;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement