Ejemplo n.º 1
0
        private void AcceptCallback(IAsyncResult result)
        {
            if (Listener == null)
            {
                return;
            }

            try
            {
                Socket socket = Listener.EndAccept(result);      // Finish accepting the incoming connection.
                Client client = new Client(this, socket);        // Add the new connection to the dictionary.

                lock (ClientLock) Clients[socket] = client;      // add the connection to list.

                OnClientConnection(new ClientEventArgs(client)); // Raise the OnConnect event.

                client.BeginReceive(ReceiveCallback, client);    // Begin receiving on the new connection connection.
                Listener.BeginAccept(AcceptCallback, null);      // Continue receiving other incoming connection asynchronously.
            }
            catch (NullReferenceException) { } // we recive this after issuing server-shutdown, just ignore it.
            catch (Exception e)
            {
                SysCons.LogError("AcceptCallback: {0}", e);
            }
        }
Ejemplo n.º 2
0
 private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
 {
     if (e.IsTerminating)
     {
         SysCons.LogError("Terminating because of unhandled exception.");
     }
     else
     {
         SysCons.LogError("Caught unhandled exception.");
     }
     Console.ReadLine();
 }
Ejemplo n.º 3
0
        int load(string rdf_file, uint record_size)
        {
            byte padding;

            char[]       record;
            int          ret;
            uint         data_size;
            BinaryReader f = new BinaryReader(File.Open(rdf_file, FileMode.Open));

            if (f == null)
            {
                return(-1);
            }


            /* Read file header information then ignore it*/
            f.ReadByte();
            f.ReadInt32();
            f.ReadByte();

            record = new char[record_size - 1];
            /* Wrote custom memset method to handle 0ing out records */
            Helpers.Util.Memset(record, 0, record_size);

            /* This loops through the file reading a record into memory */
            while (f.BaseStream.Position != f.BaseStream.Length)
            {
                int n = (int)record_size;
                ret = f.Read(record, 0, n);

                if (ret == 1)
                {
                    // Havee to write the on_record function as an abstract in the base class.
                    //if (on_record(record, (uint)ret) != 0)
                    //{
                    return(-1);
                    //}
                }
                else if (f.BaseStream.Position != f.BaseStream.Length)
                {
                    SysCons.LogError("%s: error loading [%s]: read %d vs %d\n", System.Reflection.MethodBase.GetCurrentMethod().Name, rdf_file, record_size, ret);
                    return(-1);
                }
            }

            record = null;
            f      = null;

            return(0);
        }
Ejemplo n.º 4
0
        public virtual bool Listen(string bindIP, int port)
        {
            // Check if the server has been disposed.
            if (_disposed)
            {
                throw new ObjectDisposedException(this.GetType().Name, "Server has been disposed.");
            }

            // Check if the server is already listening.
            if (IsListening)
            {
                throw new InvalidOperationException("Server is already listening.");
            }

            // Create new TCP socket and set socket options.
            Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Setup our options:
            // * NoDelay - don't use packet coalescing
            // * DontLinger - don't keep sockets around once they've been disconnected
            Listener.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
            Listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);

            try
            {
                // Bind.
                Listener.Bind(new IPEndPoint(IPAddress.Parse(bindIP), port));
                this.Port = port;
            }
            catch (SocketException)
            {
                SysCons.LogError(string.Format("{0} can't bind on {1}, server shutting down..", this.GetType().Name, bindIP));
                this.Shutdown();
                return(false);
            }

            // Start listening for incoming connections.
            Listener.Listen(10);
            IsListening = true;

            // Begin accepting any incoming connections asynchronously.
            Listener.BeginAccept(AcceptCallback, null);
            return(true);
        }
Ejemplo n.º 5
0
        private void ReceiveCallback(IAsyncResult result)
        {
            Client client = result.AsyncState as Client; // Get the connection connection passed to the callback.

            if (client == null)
            {
                return;
            }

            try
            {
                int bytesRecv = client.EndReceive(result); // Finish receiving data from the socket.

                if (bytesRecv > 0)
                {
                    OnDataReceived(new ClientDataEventArgs(client, client.RecvBuffer)); // Raise the DataReceived event.

                    if (client.IsConnected)
                    {
                        client.BeginReceive(ReceiveCallback, client);                     // Begin receiving again on the socket, if it is connected.
                    }
                    else
                    {
                        RemoveClient(client, true);  // else remove it from connection list.
                    }
                }
                else
                {
                    RemoveClient(client, true);  // Connection was lost.
                }
            }
            catch (SocketException)
            {
                RemoveClient(client, true); // An error occured while receiving, connection has disconnected.
            }
            catch (Exception e)
            {
                SysCons.LogError("ReceiveCallback: {0}", e);
            }
        }
Ejemplo n.º 6
0
        public virtual int Send(Client client, byte[] buffer, int start, int count, SocketFlags flags)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            int totalBytesSent = 0;
            int bytesRemaining = buffer.Length;

            try
            {
                while (bytesRemaining > 0)                                                             // Ensure we send every byte.
                {
                    int bytesSent = client.Socket.Send(buffer, totalBytesSent, bytesRemaining, flags); // Send the remaining data.
                    if (bytesSent > 0)
                    {
                        OnDataSent(new ClientDataEventArgs(client, buffer)); // Raise the Data Sent event.
                    }
                    // Decrement bytes remaining and increment bytes sent.
                    bytesRemaining -= bytesSent;
                    totalBytesSent += bytesSent;
                }
            }
            catch (SocketException)
            {
                RemoveClient(client, true); // An error occured while sending, connection has disconnected.
            }
            catch (Exception e)
            {
                SysCons.LogError("Send: {0}", e);
            }

            return(totalBytesSent);
        }