Sockets

07/20/2011 22:31 BaussHacker#1
Socket Client
PHP Code:
public class SocketClient
    
{
        public 
SocketClient(Socket socket)
        {
            
Socket socket
        }

        public 
Socket Socket;
        public 
string IP
        
{
            
get
            
{
                try
                {
                    return (
Socket.RemoteEndPoint as IPEndPoint).Address.ToString();
                }
                catch { return 
""; }
            }
        }
        public 
void Disconnect(bool reUse)
        {
            try
            {          
                
Socket.Close();
                
Socket.Disconnect(reUse);
            }
            catch (
Exception e)
            {
                
Server.ErrorHandler.Handle(e);
            }
        }

        public 
byte[] Buffer;
        public 
object Owner;
        public 
string AuthAccount;
        public 
string AuthPassword;

        public 
void EndAccept(Socket socketIAsyncResult result)
        {
            
Socket socket.EndAccept(result);
        }
        public 
bool Connected
        
{
            
get { return Socket.Connected; }
        }
        public 
int EndReceive(IAsyncResult resultout SocketError SE)
        {
            return 
Socket.EndReceive(resultout SE);
        }

        public 
ConquerCryption Cryption;

        public 
unsafe void Send(byte[] Packet)
        {
            try
            {
                if (
Socket.Connected)
                {
                    
byte[] Data = new byte[Packet.Length];
                    
fixed (bytesrc Packetdest Data)
                        
NativeImports.MSVCRT.MEMCPY(destsrcData.Length);
                    
Cryption.Encrypt(Data);
                    
Socket.Send(Data);
                }
            }
            catch (
Exception e)
            {
                
Server.ErrorHandler.Handle(e);
            }
        }
    } 
Socket Class:
PHP Code:
public unsafe class ConquerSockets
    
{
        
Socket socket;
        
int port;
        
IPEndPoint IPE;
        
SocketInvoke InvokeHandler;
        public 
ConquerSockets(int PortSocketInvoke _InvokeHandler)
        {
            
port Port;
            
InvokeHandler _InvokeHandler;
        }
        public 
void Listen()
        {
            
socket = new Socket(AddressFamily.InterNetworkSocketType.StreamProtocolType.Tcp);
            
IPE = new IPEndPoint(IPAddress.Parse(Kernel.ServerIP), port);
            
socket.Bind(IPE);
            
socket.Listen(100);
        }

        public 
void Accept()
        {
            
socket.BeginAccept(new AsyncCallback(Accept), new SocketClient(null));
        }
        
void Accept(IAsyncResult result)
        {
            try
            {
                
SocketClient Client result.AsyncState as SocketClient;
                
Client.Buffer = new byte[1024];

                if (!
Accepted(Clientresult))
                    
Accept();

                
InvokeHandler.Invoke(ClientConquerServerProject.Enums.SocketInvokeType.Connectionnull);
                
Accept();
                
Receive(Client);
            }
            catch { }
        }

        public 
void Receive(SocketClient Client)
        {
            
Client.Socket.BeginReceive(Client.Buffer01024SocketFlags.None, new AsyncCallback(Receive), Client);
        }
        
void Receive(IAsyncResult result)
        {
            try
            {
                
SocketClient Client result.AsyncState as SocketClient;
                try
                {

                    switch (
Client.Connected)
                    {
                        case 
true:
                            {
                                
SocketError error;
                                
int Len Client.EndReceive(resultout error);

                                switch (
error)
                                {
                                    case 
SocketError.Success:
                                        {
                                            switch (
Len)
                                            {
                                                case 
0:
                                                    
InvokeHandler.Invoke(ClientEnums.SocketInvokeType.Disconnectionnull);
                                                    break;

                                                default:
                                                    {
                                                       if (
Len 0)//Avoid negative.
                                                       
{
                                                        
byte[] Received = new byte[Len];
                                                        
MEMCPY(ReceivedClient.BufferLen);
                                                        
InvokeHandler.Invoke(ClientEnums.SocketInvokeType.ReceiveReceived);
                                                        
Receive(Client);
                                                        }
                                                       break;
                                                    }
                                            }
                                            break;
                                        }
                                }
                                break;
                            }

                        case 
false:
                            {
                                
InvokeHandler.Invoke(ClientEnums.SocketInvokeType.Disconnectionnull);
                                break;
                            }
                    }
                }
                catch
                {
                    
InvokeHandler.Invoke(ClientEnums.SocketInvokeType.Disconnectionnull);
                }
            }
            catch (
Exception e) { Server.ErrorHandler.Handle(e); }
        }

        
bool Accepted(SocketClient ClientIAsyncResult result)
        {
            try
            {
                
Client.EndAccept(socketresult);
                return 
true;
            }
            catch
            {
                return 
false;
            }
        }

        
void MEMCPY(byte[] Receivedbyte[] Bufferint Len)
        {
            
fixed (bytepointer Receivedbuffer Buffer)
                
MSVCRT.MEMCPY(pointerbufferLen);
        }
    } 
Socket Events:
PHP Code:
    public delegate void Connection(SocketClient Client);
    public 
delegate void ReceivePacket(SocketClient Clientbyte[] Packet);
    public 
delegate void Disconnection(SocketClient Client);

    public class 
SocketInvoke
    
{
        
Connection con;
        
ReceivePacket rec;
        
Disconnection disc;

        public 
SocketInvoke(Connection connectionReceivePacket receiveDisconnection disconnection)
        {
            
con connection;
            
rec receive;
            
disc disconnection;
        }

        
/// <summary>
        /// Invoking socket events.
        /// </summary>
        /// <param name="Client">The socket client.</param>
        /// <param name="invoke">The socket event invoke type.</param>
        /// <param name="Packet">The packet to invoke for receive. Can be null for connection & disconnection</param>
        
public void Invoke(SocketClient ClientEnums.SocketInvokeType invokebyte[] Packet)
        {
            switch (
invoke)
            {
                case 
ConquerServerProject.Enums.SocketInvokeType.Connection:
                    {
                        if (
con != null)
                            
con.Invoke(Client);
                        break;
                    }

                case 
ConquerServerProject.Enums.SocketInvokeType.Receive:
                    {
                        if (
rec != null)
                            
rec.Invoke(ClientPacket);
                        break;
                    }

                case 
ConquerServerProject.Enums.SocketInvokeType.Disconnection:
                    {
                        if (
disc != null)
                            
disc.Invoke(Client);
                        break;
                    }
            }
        }
    } 
Network Process:
PHP Code:
public class NetworkProcess_Auth
    
{
        public static 
void ProcessConnection(SocketClient Client)
        {
        }
        public static 
void ProcessPacket(SocketClient Clientbyte[] Packet)
        {
        }

        public static 
void ProcessDisconnection(SocketClient Client)
        { 
        }
    }
public class 
NetworkProcess_Game
    
{
        public static 
void ProcessConnection(SocketClient Client)
        {
        }
        public static 
void ProcessPacket(SocketClient Clientbyte[] Packet)
        {
        }

        public static 
void ProcessDisconnection(SocketClient Client)
        { 
        }
    } 
Useage:
PHP Code:
            #region Sockets
            
ConquerSockets authsocket = new ConquerSockets(Kernel.AuthServerPort, new SocketInvoke(
                new 
Connection(Network.NetworkProcess_Auth.ProcessConnection),
                new 
ReceivePacket(Network.NetworkProcess_Auth.ProcessPacket),
                new 
Disconnection(Network.NetworkProcess_Auth.ProcessDisconnection)));
            
authsocket.Listen();
            
authsocket.Accept();

            
ConquerSockets gamesocket = new ConquerSockets(Kernel.GameServerPort, new SocketInvoke(
                new 
Connection(Network.NetworkProcess_Game.ProcessConnection),
                new 
ReceivePacket(Network.NetworkProcess_Game.ProcessPacket),
                new 
Disconnection(Network.NetworkProcess_Game.ProcessDisconnection)));
            
gamesocket.Listen();
            
gamesocket.Accept();
            
#endregion 
Native Import:
PHP Code:
    public unsafe class MSVCRT
    
{
        [
DllImport("msvcrt.dll"EntryPoint "memcpy"CallingConvention CallingConvention.CdeclSetLastError false)]
        public static 
extern unsafe voidMEMCPY(voiddestvoidsrcint size);
    } 
Enumerator:
PHP Code:
    public enum SocketInvokeType
    
{
        
Connection,
        
Receive,
        
Disconnection
    

Figure out how to use it yourself.

Help:
[Only registered and activated users can see links. Click Here To Register...]
[Only registered and activated users can see links. Click Here To Register...]
[Only registered and activated users can see links. Click Here To Register...]
07/20/2011 23:32 Korvacs#2
Your receive method needs completely redesigning....
07/20/2011 23:53 BaussHacker#3
Quote:
Originally Posted by Korvacs View Post
Your receive method needs completely redesigning....
I know, that's why I left this as it was. :) but you could at least point to what's wrong etc.
07/21/2011 00:03 12tails#4
its a great start for who wants to learn at last.... good job ;D
07/21/2011 00:08 BaussHacker#5
Quote:
Originally Posted by 12tails View Post
its a great start for who wants to learn at last.... good job ;D
Yea and thank you. :D
07/21/2011 11:32 KraHen#6
First of all the switches don`t make any sense.
07/21/2011 11:39 Korvacs#7
Quote:
Originally Posted by BaussHacker View Post
I know, that's why I left this as it was. :) but you could at least point to what's wrong etc.
2 try/catch statements in the receive function where checks would do, and switches where if statements will do to name the most obvious.
07/21/2011 12:22 Mr_PoP#8
why do you use unsafe anyways!? your not using C/C++ lol, there is no point in using unsafe in C# unless you really needs it 0.0
07/21/2011 12:35 Korvacs#9
Quote:
Originally Posted by Y u k i View Post
Every bit counts. Thats why therer is unsafe code and switches in it. Acctually its faster that way
The compiler will decide if a switch or if/else try is faster at compile time, and in this case i can almost guarantee that an if/else will be the fastest method because there aren't enough values to justify a switch.
07/21/2011 12:48 Mr_PoP#10
unsafe code it's too messy in c#, and if you are using it because you think you're getting better performance ,in reality, while it might be better, it's not noticeably better, it's a hell of a lot worse to maintain though.

and don't use memcpy on managed memory :P , anyways it's seems OK but try to avoid any unsafe code in you're C# source :)
07/21/2011 18:58 Korvacs#11
Quote:
Originally Posted by Y u k i View Post
Its not like i dont belive you, but where do you get your informations from? Valid ressoruces would help me learn indeed.
Research, the internet, msdn, google, stackoverflow, just search what it is you want to read up on and perform tests for yourself to confirm what you have read.
07/21/2011 19:32 BaussHacker#12
Quote:
Originally Posted by Korvacs View Post
Research, the internet, msdn, google, stackoverflow, just search what it is you want to read up on and perform tests for yourself to confirm what you have read.
Code project is also good, but Stackoverflow is my favorite. It has a lot good things.
07/22/2011 02:08 hady#13
thank you for your release
07/26/2011 12:36 kinggame201#14
plz can any one told me haw to use it ?
07/26/2011 19:14 BaussHacker#15
Quote:
Originally Posted by kinggame201 View Post
plz can any one told me haw to use it ?
You put it in your source. If you don't know how to use it, then you will probably not be able to use it.