Ejemplo n.º 1
0
        public void Begin()
        {
            try
            {
                // Init socket for raw, IP based network listening.
                _socket = new Socket(AddressFamily.InterNetwork,
                                     SocketType.Raw,
                                     ProtocolType.IP);

                // Bind socket to IP and port.
                _socket.Bind(new IPEndPoint(IPAddress, Port));

                /* Configure socket to listen on all IP packets
                ** and include headers. */
                _socket.SetSocketOption(SocketOptionLevel.IP,
                                        SocketOptionName.HeaderIncluded,
                                        true);

                // State object for async callback.
                SocketStateObject monObj = new SocketStateObject(_socket,
                                                                 BufferSize);

                // Set size of receive data buffer of socket.
                _socket.ReceiveBufferSize = BufferSize;

                /* Configure IO control to receive all incoming
                ** aswell as all out going data. */
                _socket.IOControl(IOControlCode.ReceiveAll,
                                  RCVALL_ON,
                                  RCVALL_ON);

                /* Start receiving data from clients.
                ** Store connection data in monObj.Data.
                ** Set data offset to 0 and use user defined
                ** buffer size. Do not pass any socket flags.
                ** Assign async callback and pass monObj as
                ** State object of the connection. */
                _socket.BeginReceive(monObj.Data,
                                     0, BufferSize,
                                     SocketFlags.None,
                                     new AsyncCallback(OnReceive),
                                     monObj);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Ejemplo n.º 2
0
        /* Async callback for Socket.BeginReceive.
        ** Stops when _continue is set to FALSE.
        ** IAsyncResult.AsyncState contains a SocketStateObject.
        ** Raises the PacketReceived event after parsing a valid packet.
        ** Raises the OnError event if anything failes. */
        private void OnReceive(IAsyncResult ar)
        {
            /* Get SocketStateObject instance stored in
            ** the IAsyncResult.AsyncState object member. */
            SocketStateObject monObj = ar.AsyncState as SocketStateObject;

            if (null == monObj)
            {
                return;
            } /* Check if SocketStateObject is null. */

            if (!_continue)
            {
                TryRelease(monObj.Socket);
                return;
            } /* Continue receiving? */

            try
            {
                // Get socket from SocketStateObject.
                Socket socket = monObj.Socket;
                if (null == socket)
                {
                    return;
                } /* Check if received Socket is null. */

                // Stores any socket error.
                SocketError err;
                // Amount of bytes received from Socket.
                int nReceived = socket.EndReceive(ar, out err);
                // Allocate byte array to store received bytes.
                byte[] bytesReceived = new byte[nReceived];
                // Event args for PacketEventArgs.
                PacketEventArgs ipArgs = null;

                if (1 > nReceived)
                {
                    if (SocketError.Success == err)
                    {
                        // Assign SocketError.NoData.
                        err = SocketError.NoData;
                    } /* Check if we ran into any errors. */

                    /* Create event args with no header object,
                    ** the IP address, the port and the SocketError. */
                    ipArgs = new PacketEventArgs(null,
                                                 IPAddress,
                                                 Port,
                                                 err);
                } /* No data received. */
                else
                {
                    // Copy received bytes to array.
                    Buffer.BlockCopy(monObj.Data,
                                     0,
                                     bytesReceived,
                                     0,
                                     nReceived);

                    /* Create event args with header object,
                    ** IP address, port and no error. */
                    ipArgs = new PacketEventArgs(bytesReceived,
                                                 IPAddress,
                                                 Port);
                } /* Data received. */

                // Raise event.
                OnPacketReceived(ipArgs);
                // Create new SocketStateObject instance.
                monObj = new SocketStateObject(socket, BufferSize);
                // Continue receiving raw packets.
                socket.BeginReceive(monObj.Data, 0,
                                    BufferSize,
                                    SocketFlags.None,
                                    new AsyncCallback(OnReceive),
                                    monObj);
            }
            catch (Exception ex) {
                // Create new error event args.
                var errArgs = new PacketErrorEventArgs(
                    ex, _socket, IPAddress, Port);
                // Raise error event.
                OnErrorInternal(errArgs);
            }
        }