Register for your free account! | Forgot your password?

Go Back   elitepvpers > Coders Den > Coding Releases
You last visited: Today at 18:30

  • Please register to post and access all features, it's quick, easy and FREE!

Advertisement



SocketWrapper [C#]

Discussion on SocketWrapper [C#] within the Coding Releases forum part of the Coders Den category.

Reply
 
Old   #1
 
elite*gold: 20
Join Date: Aug 2005
Posts: 1,734
Received Thanks: 1,001
SocketWrapper [C#]

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);
tanelipe is offline  
Thanks
5 Users
Old 11/20/2010, 01:29   #2
 
elite*gold: 0
Join Date: Aug 2010
Posts: 951
Received Thanks: 76
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?
denominator is offline  
Old 11/20/2010, 11:23   #3
 
elite*gold: 42
Join Date: Jun 2008
Posts: 5,425
Received Thanks: 1,888
Code:
Host == ""
Code:
String.IsNullOrEmpty(Host)
kk? ;>

And there is a cool thing called comments, you should use them :>
MoepMeep is offline  
Old 11/22/2010, 13:41   #4
 
elite*gold: 0
Join Date: Sep 2006
Posts: 248
Received Thanks: 110
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.
backo is offline  
Old 11/24/2010, 14:21   #5
 
elite*gold: 42
Join Date: Jun 2008
Posts: 5,425
Received Thanks: 1,888
Quote:
Originally Posted by backo View Post
It's slower though.
And safer
MoepMeep is offline  
Old 11/25/2010, 02:54   #6
 
elite*gold: 0
Join Date: Sep 2006
Posts: 248
Received Thanks: 110
Quote:
Originally Posted by MoepMeep View Post
And safer


The third version is faster and safe as IsNullOrEmpty.
backo is offline  
Old 11/25/2010, 11:05   #7
 
elite*gold: 42
Join Date: Jun 2008
Posts: 5,425
Received Thanks: 1,888
Quote:
Originally Posted by backo View Post


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.
MoepMeep is offline  
Old 12/02/2010, 20:18   #8

 
x]vIrus[x's Avatar
 
elite*gold: 37
Join Date: Apr 2004
Posts: 2,154
Received Thanks: 250
hi, result:
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
x]vIrus[x is offline  
Thanks
1 User
Reply




All times are GMT +1. The time now is 18:30.


Powered by vBulletin®
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
SEO by vBSEO ©2011, Crawlability, Inc.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Support | Contact Us | FAQ | Advertising | Privacy Policy | Terms of Service | Abuse
Copyright ©2026 elitepvpers All Rights Reserved.