/// <summary> /// Starts listening on the port and sets the OnClientConnect handler /// </summary> /// <param name="port"></param> /// <param name="maxClientNum"></param> /// <param name="OnClientConnect"></param> public void Listen(int port, int maxClientNum, ExternalCallbackFunc OnClientConnect) { try { mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port); // Bind to local IP Address... mainSocket.Bind(ipLocal); // Start listening... mainSocket.Listen(maxClientNum); // Create the call back for any client connections... mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null); } catch (SocketException se) { throw new Exception("Exception caught from Listen()" + se.ToString()); } }
/// <summary> /// Establishes a wait for data event for a certain socket pack, and set the event handler /// </summary> /// <param name="socPak"></param> /// <param name="OnDataReceived"></param> public void WaitForData(SocketPack socPak, ExternalCallbackFunc OnDataReceived) { try { if (fncCallBack == null) { // Specify the call back function which is to be // invoked when there is any write activity by the // connected client fncCallBack = new AsyncCallback(OnDataReceived); } socPak.clientSocket.BeginReceive(socPak.dataBuffer, 0, socPak.dataBuffer.Length, SocketFlags.None, fncCallBack, socPak); } catch (SocketException) { throw new Exception("I can catch it"); } }