SocketWrapper [C#]

05/18/2008 13:28 tanelipe#1
Hello!
This is a SocketWrapper written in C#. At the moment it only has the ClientSocket part done, ServerSocket part should be done later today. Both Client-, & ServerSocket will be async.

If you decide to use this, comment here and tell me if there are any problems I may have missed.

You can comment on the code even if you decide not to use this.

Example usage on bottom of this post.

Code:
/**
 * Author : tanelipe
 * Written in 18.5.2008
 * */
using System;
using System.Net;
using System.Net.Sockets;

namespace SocketWrapper
{
    #region Delegates
    delegate void SocketEvent(BaseSocket Socket);
    delegate void SocketErrorEvent(BaseSocket Socket, String Error);
    #endregion
    #region BaseSocket
    class BaseSocket
    {
        #region Private Variables
        private int m_UID = -1;
        private byte[] m_Buffer;
        private byte[] m_Packet;
        private Socket m_Socket;
        #endregion
        /// <summary>
        /// Initializes a new BaseSocket.
        /// </summary>
        /// <param name="BufferSize">How much data the buffer can handle.</param>
        public BaseSocket(uint BufferSize)
        {
            m_Buffer = new byte[BufferSize];
        }
        /// <summary>
        /// UniqueID
        /// </summary>
        public int UID
        {
            get { return m_UID; }
            set { m_UID = value; }
        }
        /// <summary>
        /// Packet data is first stored here.
        /// </summary>
        public byte[] Buffer
        {
            get { return m_Buffer; }
            set { m_Buffer = value; }

        }
        /// <summary>
        /// Packet data copied from Buffer
        /// </summary>
        public byte[] Packet
        {
            get { return m_Packet; }
            set { m_Packet = value; }

        }
        public Socket Client
        {
            get { return m_Socket; }
            set { m_Socket = value; }
        }
    }
    #endregion
    #region ClientSocket
    class ClientSocket
    {
        public event SocketEvent onClientConnected;
        public event SocketEvent onReceivePacket;
        public event SocketErrorEvent onSocketError;

        public String Host = "";
        public UInt16 Port = 0;

        private BaseSocket Socket;

        private Boolean Initialised = false;


        public ClientSocket()
        {
            Socket = new BaseSocket(0xFFFF);
            Socket.Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Initialised = true;
        }
        public void Send(byte[] Packet)
        {
            if (!Socket.Client.Connected)
                return;
            Socket.Client.Send(Packet);
        }
        public void Connect()
        {
            if (Host == "" || Port == 0)
            {
                throw new Exception(Host == "" ? "'Host' can't be an emptry string." : "'Port' can't be 0.");
            }
            IPAddress RemoteHost;
            if (!IPAddress.TryParse(Host, out RemoteHost))
                throw new Exception("Could not parse 'Host' into IPAddress.");
            if (!Initialised)
            {
                Socket = new BaseSocket(0xFFFF);
                Socket.Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            }
            Socket.Client.BeginConnect(RemoteHost, Port, new AsyncCallback(SocketConnecting), Socket);
        }
        private void SocketConnecting(IAsyncResult res)
        {
            BaseSocket Socket = (BaseSocket)res.AsyncState;
            try
            {
                Socket.Client.EndConnect(res);
                if (onClientConnected != null)
                    onClientConnected.Invoke(Socket);
                Socket.Client.BeginReceive(Socket.Buffer, 0, 0xFFFF, SocketFlags.None, new AsyncCallback(ReceivePacket), Socket);
            }
            catch (Exception ConnectError)
            {
                if (onSocketError != null)
                    onSocketError.Invoke(Socket, ConnectError.Message);
            }
        }
        private void ReceivePacket(IAsyncResult res)
        {
            BaseSocket Socket = (BaseSocket)res.AsyncState;
            try
            {
                SocketError Mode;
                int Size = Socket.Client.EndReceive(res, out Mode);
                if (Mode == SocketError.Success && Size > 0)
                {
                    Socket.Packet = new byte[Size];
                    for (int i = 0; i < Size; i++)
                        Socket.Packet[i] = Socket.Buffer[i];
                    if (onReceivePacket != null)
                        onReceivePacket.Invoke(Socket);
                    Socket.Client.BeginReceive(Socket.Buffer, 0, 0xFFFF, SocketFlags.None, new AsyncCallback(ReceivePacket), Socket);
                }
            }
            catch (Exception e)
            {
                if (onSocketError != null)
                    onSocketError.Invoke(Socket, e.Message);
            }
        }
    }
    #endregion
}
Usage :

Code:
                ClientSocket Socket = new ClientSocket();
                Socket.Host = "123.45.67.89";
                Socket.Port = 9958;
                Socket.Connect();
                Socket.onClientConnected += new SocketEvent(Socket_onClientConnected);
                Socket.onReceivePacket += new SocketEvent(Socket_onReceivePacket);
                Socket.onSocketError += new SocketErrorEvent(Socket_onSocketError);
11/20/2010 01:29 denominator#2
Code:
ClientSocket Socket = new ClientSocket();
                Socket.Host = "123.45.67.89";
                Socket.Port = 9958;
                Socket.Connect();
                Socket.onClientConnected += new SocketEvent(Socket_onClientConnected);
                Socket.onReceivePacket += new SocketEvent(Socket_onReceivePacket);
                Socket.onSocketError += new SocketErrorEvent(Socket_onSocketError);
A little confused as to where this goes? Do I add a new class for it? Or do I add it to the first code?
11/20/2010 11:23 MoepMeep#3
Code:
Host == ""
Code:
String.IsNullOrEmpty(Host)
kk? ;>

And there is a cool thing called comments, you should use them :>
11/22/2010 13:41 backo#4
Quote:
Originally Posted by MoepMeep View Post
Code:
Host == ""
Code:
String.IsNullOrEmpty(Host)
kk? ;>

And there is a cool thing called comments, you should use them :>
It's slower though.
11/24/2010 14:21 MoepMeep#5
Quote:
Originally Posted by backo View Post
It's slower though.
And safer ;)
11/25/2010 02:54 backo#6
Quote:
Originally Posted by MoepMeep View Post
And safer ;)
[Only registered and activated users can see links. Click Here To Register...]

The third version is faster and safe as IsNullOrEmpty.
11/25/2010 11:05 MoepMeep#7
Quote:
Originally Posted by backo View Post
[Only registered and activated users can see links. Click Here To Register...]

The third version is faster and safe as IsNullOrEmpty.
agree.

Quote:
=== Performance test for string.IsNullOrEmpty in C# ===
IsNullOrEmpty was not the fastest way to check strings.
Based on .NET 3.5 SP1.
Got anything for 4.0? Don't know if they changed anything their, not using C# that much.
12/02/2010 20:18 x]vIrus[x#8
hi, result: [Only registered and activated users can see links. Click Here To Register...]
code:
Code:
            for (int i = 0; i++ < 1000000000; )
            {

            }
            string s = "eheeh";
            List<string> l = new List<string>();
            DateTime dt = DateTime.Now;

            for (int i = 0; i++ < 1000000000; )
            {
                if (string.IsNullOrEmpty(s)) ;
            }

            l.Add((DateTime.Now-dt).ToString());
            dt = DateTime.Now;
            
            for (int i = 0; i++ < 1000000000; )
            {
                if (s == null || s == "") ;
            }
            
            l.Add((DateTime.Now-dt).ToString());
            dt = DateTime.Now;
            
            for (int i = 0; i++ < 1000000000; )
            {
                if (s == null || s.Length==0) ;
            }
            
            l.Add((DateTime.Now-dt).ToString());
            dt = DateTime.Now;
            
            for (int i = 0; i++ < 1000000000; )
            {
                if (!(s != null && s.Length>0)) ;
            }
            l.Add((DateTime.Now-dt).ToString());
            MessageBox.Show(string.Join("\n", l.ToArray()));
going by this code, isnullorempty is the fastest one,
tested in 4.0