Advertisement
Guest User

TCP Socket Server, ObjectDisposedException

a guest
Jun 5th, 2014
334
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.34 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7.  
  8. namespace Sandbox
  9. {
  10.     class Program
  11.     {
  12.         private static IDictionary<Socket, IList<Socket>> connectedClients;
  13.  
  14.         static void Main(string[] args)
  15.         {
  16.             // Create connected client storage.
  17.             connectedClients = new Dictionary<Socket, IList<Socket>>();
  18.  
  19.             // Create the socket.
  20.             Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  21.             connectedClients.Add(listener, new List<Socket>());
  22.  
  23.             // Bind it to address.
  24.             listener.Bind(new IPEndPoint(IPAddress.Any, 1337));
  25.  
  26.             // Listen to it.
  27.             listener.Listen(100);
  28.  
  29.             Console.WriteLine("Listening on {0}...", listener.LocalEndPoint);
  30.  
  31.             // Create a reusable event handler.
  32.             SocketAsyncEventArgs e = new SocketAsyncEventArgs();
  33.  
  34.             // Bind event to be called once the Async operation ends.
  35.             e.Completed += AcceptCallback;
  36.  
  37.             // Begin asynchronous accept.
  38.             listener.AcceptAsync(e);
  39.  
  40.             Console.WriteLine("Accepting on {0}...", listener.LocalEndPoint);
  41.  
  42.             Console.ReadKey();
  43.         }
  44.  
  45.         private static void AcceptCallback(object sender, SocketAsyncEventArgs e)
  46.         {
  47.             // The server we're working with.
  48.             Socket listener = (Socket)sender;
  49.             IPEndPoint serverCoordinates = listener.LocalEndPoint as IPEndPoint;
  50.  
  51.             // Client, that has been accepted.
  52.             Socket client = e.AcceptSocket;
  53.             IPEndPoint clientCoordinates = client.RemoteEndPoint as IPEndPoint;
  54.  
  55.             if (client.Connected)
  56.             {
  57.                 Console.WriteLine("{0} connected to {1}.", clientCoordinates, serverCoordinates);
  58.                 connectedClients[listener].Add(client);
  59.  
  60.                 try
  61.                 {
  62.                     Debug.Assert(client != null);
  63.  
  64.                     // Lets work!
  65.                     client.Send(Encoding.ASCII.GetBytes(String.Format("Welcome {0}!", clientCoordinates)));
  66.  
  67.                     SocketAsyncEventArgs ce = new SocketAsyncEventArgs();
  68.                     ce.Completed += ReceiveCallback;
  69.                     ce.SetBuffer(new Byte[4096], 0, 4096);
  70.                     ce.UserToken = listener;
  71.  
  72.                     // Bind listening event.
  73.                     client.ReceiveAsync(ce);
  74.  
  75.                     Console.WriteLine("Listening to {0} on {1}...", clientCoordinates, serverCoordinates);
  76.                 }
  77.                 catch (Exception ex)
  78.                 {
  79.                     Console.WriteLine("Exception encountered:");
  80.                     Console.WriteLine(ex);
  81.                 }
  82.                 finally
  83.                 {
  84.                     // Reuse the event arguments.
  85.                     e.AcceptSocket = null;
  86.                 }
  87.  
  88.                 // Listen for the next connection.
  89.                 listener.AcceptAsync(e);
  90.             }
  91.         }
  92.  
  93.         private static void ReceiveCallback(object sender, SocketAsyncEventArgs e)
  94.         {
  95.             Socket client = (Socket)sender;
  96.             Socket listener = (Socket)e.UserToken;
  97.  
  98.             string message = Encoding.ASCII.GetString(e.Buffer, e.Offset, e.BytesTransferred);
  99.  
  100.             IPEndPoint clientCoordinates = client.RemoteEndPoint as IPEndPoint;
  101.             IPEndPoint serverCoordinates = listener.LocalEndPoint as IPEndPoint;            
  102.  
  103.             Console.WriteLine("{0} bytes from {1} on {2}", e.BytesTransferred, clientCoordinates, serverCoordinates);
  104.  
  105.             if (e.BytesTransferred > 0)
  106.             {
  107.                 Console.WriteLine("{0} from {1} on {2}", message, clientCoordinates, serverCoordinates);
  108.             }
  109.  
  110.             if (message == "disconnect" || e.BytesTransferred == 0)
  111.             {
  112.                 try
  113.                 {
  114.                     Console.WriteLine("{0} on {1} requested to be disconnected.", clientCoordinates, serverCoordinates);
  115.                     client.Send(Encoding.ASCII.GetBytes("Disconnecting..."));
  116.                     client.Disconnect(false);
  117.                     Console.WriteLine("{0} on {1} disconnected.", clientCoordinates, serverCoordinates);
  118.                 }
  119.                 catch (Exception)
  120.                 {
  121.                     // Throw if client has closed, so it is not necessary to catch.
  122.                 }
  123.                 finally
  124.                 {
  125.                     connectedClients[listener].Remove(client);
  126.  
  127.                     client.Close();
  128.                     Console.WriteLine("{0} on {1} closed.", clientCoordinates, serverCoordinates);
  129.  
  130.                     e.Dispose();
  131.                 }
  132.  
  133.                 return;
  134.             }
  135.  
  136.             if (message == "stop")
  137.             {
  138.                 try
  139.                 {
  140.                     Console.WriteLine("{0} on {1} requested to close the server.", clientCoordinates, serverCoordinates);
  141.                     client.Send(Encoding.ASCII.GetBytes("Shutting down your server..."));
  142.                     client.Disconnect(false);
  143.                     Console.WriteLine("{0} on {1} disconnected.", clientCoordinates, serverCoordinates);
  144.                 }
  145.                 catch (Exception)
  146.                 {
  147.                     // ...
  148.                 }
  149.                 finally
  150.                 {
  151.                     connectedClients[listener].Remove(client);
  152.  
  153.                     client.Close();
  154.                     Console.WriteLine("{0} on {1} closed.", clientCoordinates, serverCoordinates);
  155.  
  156.                     Console.WriteLine("Remaining clients on {0}: {1}", serverCoordinates, connectedClients[listener].Count);
  157.  
  158.                     // Disconnect remaining clients.
  159.                     for (int i = 0; i < connectedClients[listener].Count; i++)
  160.                     {
  161.                         Socket connectedClient = connectedClients[listener][i];
  162.  
  163.                         IPEndPoint connectedClientCoordinates = connectedClient.RemoteEndPoint as IPEndPoint;
  164.  
  165.                         try
  166.                         {
  167.                             connectedClient.Send(Encoding.ASCII.GetBytes("Server shutting down..."));
  168.                             connectedClient.Disconnect(false);
  169.                             Console.WriteLine("{0} on {1} disconnected by shutdown.", connectedClientCoordinates, serverCoordinates);
  170.                         }
  171.                         catch (Exception)
  172.                         {
  173.  
  174.                         }
  175.                         finally
  176.                         {
  177.                             connectedClients[listener].Remove(connectedClient);
  178.  
  179.                             connectedClient.Close();
  180.                             Console.WriteLine("{0} on {1} closed by shutdown.", connectedClientCoordinates, serverCoordinates);
  181.                         }
  182.                     }
  183.  
  184.                     Console.WriteLine("{0} closing...", serverCoordinates);
  185.                     listener.Close();
  186.                     Console.WriteLine("{0} closed.", serverCoordinates);
  187.  
  188.                     connectedClients.Remove(listener);
  189.                 }
  190.  
  191.                 return;
  192.             }
  193.  
  194.             // Listen for next.
  195.             client.ReceiveAsync(e);
  196.         }
  197.     }
  198. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement