Anyone can optimize this code ?

11/26/2013 10:30 marcbacor6666#1
Kindly make this code better guys. I want a port refresher that uses less Cpu usage.


Code:
static void Port_Refresher()
        {
            while (true)
            {
                {
                    AuthServer.Disable();
                    AuthServer = null;
                    AuthServer = new AsyncSocket(AuthPort);
                    AuthServer.OnClientConnect += new Action<Interfaces.ISocketWrapper>(AuthServer_AnnounceNewConnection);
                    AuthServer.OnClientReceive += new Action<byte[], Interfaces.ISocketWrapper>(AuthServer_AnnounceReceive);
                    AuthServer.OnClientDisconnect += new Action<Interfaces.ISocketWrapper>(AuthServer_AnnounceDisconnection);//loads all
                    GameServer.Disable();
                    GameServer = null;
                    GameServer = new AsyncSocket(GamePort);
                    GameServer.OnClientConnect += new Action<Interfaces.ISocketWrapper>(GameServer_AnnounceNewConnection);
                    GameServer.OnClientReceive += new Action<byte[], Interfaces.ISocketWrapper>(GameServer_AnnounceReceive);
                    GameServer.OnClientDisconnect += new Action<Interfaces.ISocketWrapper>(GameServer_AnnounceDisconnection);
                }
                Thread.Sleep(60000);
            }
        }
or can anyone help me make a code that will check if the port is disable ?

sample if the port is disabled the code will run to enable it automatically.

something like this.




Code:
if ((AuthServer == null) || (GameServer == null))
                            {
                                AuthServer = new AsyncSocket(AuthPort);
                                AuthServer.OnClientConnect += new Action<Interfaces.ISocketWrapper>(AuthServer_AnnounceNewConnection);
                                AuthServer.OnClientReceive += new Action<byte[], Interfaces.ISocketWrapper>(AuthServer_AnnounceReceive);
                                AuthServer.OnClientDisconnect += new Action<Interfaces.ISocketWrapper>(AuthServer_AnnounceDisconnection);
                                GameServer = new AsyncSocket(GamePort);
                                GameServer.OnClientConnect += new Action<Interfaces.ISocketWrapper>(GameServer_AnnounceNewConnection);
                                GameServer.OnClientReceive += new Action<byte[], Interfaces.ISocketWrapper>(GameServer_AnnounceReceive);
                                GameServer.OnClientDisconnect += new Action<Interfaces.ISocketWrapper>(GameServer_AnnounceDisconnection);
                                break;
                            }



Quote:
This is my AsyncSocket.cs
Code:
namespace Co2.Network.Sockets
{
    using Co2;
    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    using Co2.Interfaces;

    public class AsyncSocket
    {
        private int backlog;
        private int clientbuffersize = 0xffff;
        private WinSocket Connection = new WinSocket();
        private bool enabled;
        public bool GameServer = false;
        public event Action<Interfaces.ISocketWrapper> OnClientConnect;
        public event Action<Interfaces.ISocketWrapper> OnClientDisconnect;
        public event Action<byte[], Interfaces.ISocketWrapper> OnClientReceive;
        private ushort port;

  

        public AsyncSocket(ushort port)
        {
            if (!this.enabled)
            {
                this.port = port;
                this.Connection.Bind(new IPEndPoint(IPAddress.Any, this.port));
                this.Connection.Listen(100);
                this.Connection.BeginAccept(new AsyncCallback(this.AsyncConnect), null);
                this.enabled = true;
            }
        }


        private void AsyncConnect(IAsyncResult res)
        {
            AsyncSocketWrapper sender = null;
            try
            {
                sender = new AsyncSocketWrapper();
                sender.Create(this.Connection.EndAccept(res));
                if (sender.Socket == null)
                {
                    this.Connection.BeginAccept(new AsyncCallback(this.AsyncConnect), null);
                    return;
                }
                if (this.OnClientConnect != null)
                {
                    this.OnClientConnect(sender);
                }
                sender.Socket.BeginReceive(sender.Buffer, 0, sender.Buffer.Length, SocketFlags.None, new AsyncCallback(this.AsyncReceive), sender);

                this.Connection.BeginAccept(new AsyncCallback(this.AsyncConnect), null);
            }
            catch (SocketException e)
            {
                Program.SaveException(e);
                Co2.Console.WriteLine(e);
                if (this.enabled)
                {
                    this.Connection.BeginAccept(new AsyncCallback(this.AsyncConnect), null);
                }
            }
            catch (ObjectDisposedException e)
            {
                Program.SaveException(e);
                Co2.Console.WriteLine(e);
            }
        }

        private unsafe void AsyncReceive(IAsyncResult res)
        {
            bool was = false;
            try
            {
                SocketError error;
                AsyncSocketWrapper asyncState = (AsyncSocketWrapper)res.AsyncState;
                int RecvSize = asyncState.Socket.EndReceive(res, out error);
                if ((error == SocketError.Success) && (RecvSize > 0))
                {
                    was = true;
                    byte[] buffer = new byte[RecvSize];
                    for (int i = 0; i < RecvSize; i++)
                    {
                        buffer[i] = asyncState.Buffer[i];
                    }
                    if (this.OnClientReceive != null)
                    {
                        this.OnClientReceive(buffer, asyncState);
                    }

                    asyncState.Socket.BeginReceive(asyncState.Buffer, 0, asyncState.Buffer.Length, SocketFlags.None, new AsyncCallback(this.AsyncReceive), asyncState);
                }
                else
                {
                    this.InvokeDisconnect(asyncState);
                }
            }
            catch (SocketException e)
            {
                Program.SaveException(e);
                Co2.Console.WriteLine(e);
                if (was)
                {
                    AsyncSocketWrapper asyncState = (AsyncSocketWrapper)res.AsyncState;
                    asyncState.Socket.BeginReceive(asyncState.Buffer, 0, asyncState.Buffer.Length, SocketFlags.None, new AsyncCallback(this.AsyncReceive), asyncState);
                }
            }
            catch (ObjectDisposedException e)
            {
                Program.SaveException(e);
                Co2.Console.WriteLine(e);
            }
            catch (Exception e)
            {
                Program.SaveException(e);
            }
        }

        public void Disable()
        {
            if (this.enabled)
            {
                this.Connection.Disable();
                this.enabled = false;
            }
        }

        public void Enable()
        {
            if (!this.enabled)
            {
                this.Connection.Bind(new IPEndPoint(IPAddress.Any, this.port));
                this.Connection.Listen(this.backlog);
                this.Connection.BeginAccept(new AsyncCallback(this.AsyncConnect), null);
                this.enabled = true;
            }
        }

        private void enabledCheck(string Variable)
        {
            if (this.enabled)
            {
                throw new Exception("Cannot modify " + Variable + " while socket is enabled.");
            }
        }

        public void InvokeDisconnect(AsyncSocketWrapper Client)
        {
            if (Client != null)
            {
                try
                {
                    if (Client.Socket.Connected)
                    {
                        Client.Socket.Shutdown(SocketShutdown.Both);
                        Client.Socket.Close();
                        if (this.OnClientDisconnect != null)
                        {
                            this.OnClientDisconnect(Client);
                        }
                        Client.Connector = null;
                        Client = null;
                    }
                    else
                    {
                        if (this.OnClientDisconnect != null)
                        {
                            this.OnClientDisconnect(Client);
                        }
                        Client.Connector = null;
                        Client = null;
                    }
                }
                catch (ObjectDisposedException e)
                {
                    Program.SaveException(e);
                    Co2.Console.WriteLine(e);
                }
            }
        }

        public int Backlog
        {
            get
            {
                return this.backlog;
            }
            set
            {
                this.enabledCheck("Backlog");
                this.backlog = value;
            }
        }

        public int ClientBufferSize
        {
            get
            {
                return this.clientbuffersize;
            }
            set
            {
                this.enabledCheck("ClientBufferSize");
                this.clientbuffersize = value;
            }
        }

        public bool Enabled
        {
            get
            {
                return this.enabled;
            }
        }

        public ushort Port
        {
            get
            {
                return this.port;
            }
            set
            {
                this.enabledCheck("Port");
                this.port = value;
            }
        }
    }
}

Quote:
This is my Winsocket.cs
Code:
namespace Co2.Network.Sockets
{
    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Runtime.InteropServices;
    using System.Threading;

    public class WinSocket
    {
        private Socket Connection;
        public bool Disabled;
        private bool disconnected;

        public WinSocket()
        {
            this.disconnected = false;
            this.Disabled = false;
            this.Connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        public WinSocket(Socket socket)
        {
            this.disconnected = false;
            this.Disabled = false;
            this.Connection = socket;
        }

        public Socket Accept()
        {
            if (!this.Disabled)
            {
                try
                {
                    if (this.disconnected)
                    {
                        return null;
                    }
                    return this.Connection.Accept();
                }
                catch
                {
                    this.Disabled = true;
                }
            }
            return null;
        }

        public void BeginAccept(AsyncCallback async, object state)
        {
            if (!this.Disabled)
            {
                try
                {
                    if (!this.disconnected)
                    {
                        this.Connection.BeginAccept(async, state);
                    }
                }
                catch
                {
                    this.Disabled = true;
                }
            }
        }

        public void BeginReceive(byte[] buffer, int offset, int size, SocketFlags flag, AsyncCallback callback, object state)
        {
            if (!this.Disabled)
            {
                try
                {
                    if (!this.disconnected && this.Connected)
                    {
                        this.Connection.BeginReceive(buffer, offset, size, flag, callback, state);
                    }
                }
                catch
                {
                    this.Disabled = true;
                }
            }
        }

        public void Bind(EndPoint point)
        {
            if (!this.disconnected)
            {
                this.Connection.Bind(point);
            }
        }

        public void Close()
        {
        }

        public void Disable()
        {
            try
            {
                this.Disabled = true;
                this.Connection.Close();
            }
            catch
            {
                this.Disabled = true;
            }
        }

        public void Disconnect(bool reuse)
        {
            if (!this.Disabled)
            {
                try
                {
                    if (!this.disconnected)
                    {
                        this.disconnected = true;
                    }
                    else
                    {
                        return;
                    }
                    Thread.Sleep(4);
                    this.Connection.Disconnect(false);
                }
                catch
                {
                    this.Disabled = true;
                }
            }
        }

        public Socket EndAccept(IAsyncResult async)
        {
            if (!this.Disabled)
            {
                try
                {
                    if (this.disconnected)
                    {
                        return null;
                    }
                    return this.Connection.EndAccept(async);
                }
                catch
                {
                    this.Disabled = true;
                }
            }
            return null;
        }

        public int EndReceive(IAsyncResult res, out SocketError err)
        {
            err = SocketError.Disconnecting;
            if (!this.Disabled)
            {
                try
                {
                    if (!this.Usable)
                    {
                        return 0;
                    }
                    return this.Connection.EndReceive(res, out err);
                }
                catch
                {
                    this.Disabled = true;
                }
            }
            return 0;
        }

        public void Listen(int backlog)
        {
            if (!this.disconnected)
            {
                this.Connection.Listen(backlog);
            }
        }

        public int Receive(byte[] buffer)
        {
            if (this.disconnected)
            {
                return 0;
            }
            return this.Connection.Receive(buffer);
        }

        public void Send(byte[] buffer)
        {
            if (!this.Disabled)
            {
                try
                {
                    if (!this.disconnected)
                    {
                        this.Connection.Send(buffer);
                    }
                }
                catch
                {
                    this.Disabled = true;
                }
            }
        }

        public void Shutdown(SocketShutdown type)
        {
            this.Connection.Shutdown(type);
        }

        public bool Connected
        {
            get
            {
                if (!this.Disabled)
                {
                    try
                    {
                        if (this.disconnected)
                        {
                            return false;
                        }
                        return this.Connection.Connected;
                    }
                    catch
                    {
                        this.Disabled = true;
                    }
                }
                return false;
            }
        }

        public EndPoint RemoteEndPoint
        {
            get
            {
                if (this.Disabled)
                {
                    return new IPEndPoint(1L, 1);
                }
                try
                {
                    return this.Connection.RemoteEndPoint;
                }
                catch
                {
                    this.Disabled = true;
                }
                return new IPEndPoint(1L, 1);
            }
        }

        private bool Usable
        {
            get
            {
                return !this.disconnected;
            }
        }
    }
}
11/26/2013 12:23 -impulse-#2
I've got a question: what is a port refresher?

Though, why would you even what that? (Looking at your code, this question seems logical).
11/26/2013 12:35 marcbacor6666#3
Quote:
Originally Posted by -impulse- View Post
I've got a question: what is a port refresher?

Though, why would you even what that? (Looking at your code, this question seems logical).
cuz after few minutes/hours my server being online sometimes i think this

Quote:
AuthServer = new AsyncSocket(AuthPort);
AuthServer.OnClientConnect += new Action<Interfaces.ISocketWrapper>(AuthServer_Annou nceNewConnection);
AuthServer.OnClientReceive += new Action<byte[], Interfaces.ISocketWrapper>(AuthServer_AnnounceRece ive);
AuthServer.OnClientDisconnect += new Action<Interfaces.ISocketWrapper>(AuthServer_Annou nceDisconnection);
GameServer = new AsyncSocket(GamePort);
GameServer.OnClientConnect += new Action<Interfaces.ISocketWrapper>(GameServer_Annou nceNewConnection);
GameServer.OnClientReceive += new Action<byte[], Interfaces.ISocketWrapper>(GameServer_AnnounceRece ive);
GameServer.OnClientDisconnect += new Action<Interfaces.ISocketWrapper>(GameServer_Annou nceDisconnection);

stop responding no one can login untill ill command this


Code:
 case "@eonline":
                    {
                        AuthServer.Disable();
                        AuthServer = null;
                        AuthServer = new AsyncSocket(AuthPort);
                        AuthServer.OnClientConnect += new Action<Interfaces.ISocketWrapper>(AuthServer_AnnounceNewConnection);
                        AuthServer.OnClientReceive += new Action<byte[], Interfaces.ISocketWrapper>(AuthServer_AnnounceReceive);
                        AuthServer.OnClientDisconnect += new Action<Interfaces.ISocketWrapper>(AuthServer_AnnounceDisconnection);
                        GameServer.Disable();
                        GameServer = null;
                        GameServer = new AsyncSocket(GamePort);
                        GameServer.OnClientConnect += new Action<Interfaces.ISocketWrapper>(GameServer_AnnounceNewConnection);
                        GameServer.OnClientReceive += new Action<byte[], Interfaces.ISocketWrapper>(GameServer_AnnounceReceive);
                        GameServer.OnClientDisconnect += new Action<Interfaces.ISocketWrapper>(GameServer_AnnounceDisconnection);
                        break;
                    }
11/26/2013 12:54 Super Aids#4
I think the problem is that an exception is thrown withn your asynchronous callbacks and thus stopping it from requesting the next callback.

Ex.
Code:
void AsyncCallback(IAsyncResult asyncResult)
{
    try
    {
        DoThings();

        BeginSomething(); // requests another callback
    }
    catch { }
}
In this case if an exception is thrown in the DoThings() method then it will never get to BeginSomething() which requests another asynchronous callback.

Instead of doing these lame workarounds, perhaps learn to debug your applications and fix them correctly.

Let me give you an example how it could be blocking people from connecting.
Code:
/// <summary>
		/// Starts to accept connections.
		/// </summary>
		private void Accept()
		{
			serverSocket.BeginAccept(new AsyncCallback(Accept_Callback), null);
		}
		
		/// <summary>
		/// The callback from Accept()
		/// </summary>
		/// <param name="asyncResult">The async result.</param>
		private void Accept_Callback(IAsyncResult asyncResult)
		{
			try
			{
                                // If this code throws an exception ...
                                // Then Accept() is never called ...
				Socket accepted = serverSocket.EndAccept(asyncResult);
				if (accepted.Connected)
				{
					SocketClient sClient = new SocketClient(accepted, socketEvents);
					if (socketEvents.OnConnection.Invoke(sClient))
						sClient.Receive();
				}

			        Accept(); // This will accept new connections, if this is not called, no more players can connect
			}
			catch { }
		}
And the solution?
Simply move the Accept() outside of the try/catch block.
Code:
/// <summary>
		/// The callback from Accept()
		/// </summary>
		/// <param name="asyncResult">The async result.</param>
		private void Accept_Callback(IAsyncResult asyncResult)
		{
			try
			{
				Socket accepted = serverSocket.EndAccept(asyncResult);
				if (accepted.Connected)
				{
					SocketClient sClient = new SocketClient(accepted, socketEvents);
					if (socketEvents.OnConnection.Invoke(sClient))
						sClient.Receive();
				}
			}
			catch { }
			[B][I][COLOR="Orange"]Accept();[/COLOR][/I][/B]
		}
I am not saying this is the problem, but it's the only logical explanation I could think of.
11/26/2013 13:04 marcbacor6666#5
thank you for the explanation :)

lol cant find it.

anyone wanna help
11/27/2013 20:14 abdoumatrix#6
Quote:
Originally Posted by marcbacor6666 View Post
thank you for the explanation :)

lol cant find it.

anyone wanna help
what they u want to say that ur source 's sockets , packets handling sucks

u should take alook at SuperAids 's C# Programming Tutorials!!! Part two to know more about sockets.(check his sign..).
11/28/2013 05:19 marcbacor6666#7
Quote:
Will this fixed the problem?
Quote:
Original Code that will loginfreeze the server randomly
Code:
 private unsafe void AsyncReceive(IAsyncResult res)
        {
            bool was = false;
            try
            {
                SocketError error;
                AsyncSocketWrapper asyncState = (AsyncSocketWrapper)res.AsyncState;
                int RecvSize = asyncState.Socket.EndReceive(res, out error);
                if ((error == SocketError.Success) && (RecvSize > 0))
                {
                    was = true;
                    byte[] buffer = new byte[RecvSize];
                    for (int i = 0; i < RecvSize; i++)
                    {
                        buffer[i] = asyncState.Buffer[i];
                    }
                    if (this.OnClientReceives != null)
                    {
                        this.OnClientReceives(buffer, asyncState);
                    }
                                   asyncState.Socket.BeginReceive(asyncState.Buffer, 0, asyncState.Buffer.Length, SocketFlags.None, new AsyncCallback(this.AsyncReceive), asyncState);
                }
                else
                {
                    this.InvokeDisconnect(asyncState);
                }

            }
            catch (SocketException e)
            {
                Program.SaveException(e);
            }
            catch (ObjectDisposedException e)
            {
                Program.SaveException(e);
            }
            catch (OutOfMemoryException e)
            {
                Program.SaveException2(e);
            }
            catch (Exception e)
            {
                Program.SaveException(e);
                if (was)
                {
                    AsyncSocketWrapper asyncState = (AsyncSocketWrapper)res.AsyncState;
                    asyncState.Socket.BeginReceive(asyncState.Buffer, 0, asyncState.Buffer.Length, SocketFlags.None, new AsyncCallback(this.AsyncReceive), asyncState);
                }
            }
        }

Quote:
Modified , will this fixed it?
Code:
 private unsafe void AsyncReceive(IAsyncResult res)
        {
            bool was = false;
            try
            {
                SocketError error;
                AsyncSocketWrapper asyncState = (AsyncSocketWrapper)res.AsyncState;
                int RecvSize = asyncState.Socket.EndReceive(res, out error);
                if ((error == SocketError.Success) && (RecvSize > 0))
                {
                    was = true;
                    byte[] buffer = new byte[RecvSize];
                    for (int i = 0; i < RecvSize; i++)
                    {
                        buffer[i] = asyncState.Buffer[i];
                    }
                    if (this.OnClientReceives != null)
                    {
                        this.OnClientReceives(buffer, asyncState);
                    }
                                   
                }
                else
                {
                    this.InvokeDisconnect(asyncState);

                }
asyncState.Socket.BeginReceive(asyncState.Buffer, 0, asyncState.Buffer.Length, SocketFlags.None, new AsyncCallback(this.AsyncReceive), asyncState);
            }
            catch (SocketException e)
            {
                Program.SaveException(e);
            }
            catch (ObjectDisposedException e)
            {
                Program.SaveException(e);
            }
            catch (OutOfMemoryException e)
            {
                Program.SaveException2(e);
            }
            catch (Exception e)
            {
                Program.SaveException(e);
                if (was)
                {
                    AsyncSocketWrapper asyncState = (AsyncSocketWrapper)res.AsyncState;
                    asyncState.Socket.BeginReceive(asyncState.Buffer, 0, asyncState.Buffer.Length, SocketFlags.None, new AsyncCallback(this.AsyncReceive), asyncState);
                }
            }
        }
11/28/2013 05:42 pro4never#8
Your code you keep posting is dealing with receiving packets from clients already connected.

Your issue is most likely that when someone fails during their initial connection attempt, the server simply stops listening for new people trying. It's not so much a freeze as the server going "well that failed, no reason to listen for any new connections"
11/28/2013 06:06 marcbacor6666#9
thank you fang thank you for your explanation, im gonna try to fixed it now thanks :)
11/28/2013 06:48 Spirited#10
Quote:
Originally Posted by marcbacor6666 View Post
thank you fang thank you for your explanation, im gonna try to fixed it now thanks :)
I believe you mean Pro4never, for I am not Chris. :p
11/28/2013 07:17 marcbacor6666#11
Quote:
Originally Posted by Fang View Post
I believe you mean Pro4never, for I am not Chris. :p
oh lol ehehehe yah i mean
Quote:
pro4never
eheheh i was reading some codes thats why :) thank you also fang for trying to help. thanks pro4never

by the way this is the code that will be turn off randomly

Code:
 GameServer = new AsyncSocket(GamePort);
                        GameServer.OnClientConnect += new Action<Interfaces.ISocketWrapper>(GameServer_AnnounceNewConnection);
                        GameServer.OnClientReceive += new Action<byte[], Interfaces.ISocketWrapper>(GameServer_AnnounceReceive);
                        GameServer.OnClientDisconnect += new Action<Interfaces.ISocketWrapper>(GameServer_AnnounceDisconnection);
11/28/2013 15:09 Super Aids#12
The problem is still not his BeginReceive, but his BeginAccept.
11/28/2013 18:08 GRASSHOPPA#13
@your initial way of handling this
i wouldn't suggest you thread.sleep for so long...or using that method to fix it in general, buttttt if you do use it you should take a look at this fancy little guide so you can learn about event handling
[Only registered and activated users can see links. Click Here To Register...]

threading.timers is another, often preferred, method of timed function calls



@fixing your jizz
i agree with super aids..you're going about solving this entirely wrong lol
11/29/2013 19:51 marcbacor6666#14
can u show me Super Aids?
11/29/2013 20:42 GRASSHOPPA#15
he already told you exactly where you are having the issue 0,0?
if you aren't even willing to attempt it why would people give you help...?
don't try to run your own server if you don't want to put in the work