Mossy's World | Weird Stuff..

Oct/09

16

C# – Easy Sockets Class

/*
* Sockets Client
* (C)2009 Daniel Moss
*
* Handles all of the Socket functions
*
*/
internal class StateObject
{
public byte[] buffer = new byte[32768];
public int BufferSize = 32767;
public StringBuilder sb = new StringBuilder();
public Socket workSocket;
}
internal class SocketsClient
{
#region Delegates
public delegate void onConnectEventHandler();
public delegate void onDataArrivalEventHandler(byte[] Data, int TotalBytes);
public delegate void onDisconnectEventHandler();
public delegate void onErrorEventHandler(string Description);
public delegate void onSendCompleteEventHandler(int DataSize);
#endregion
private static Socket  client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private static IPHostEntry ipHostInfo = Dns.GetHostEntry(”localhost”);
private static IPAddress ipAddress = ipHostInfo.AddressList[0];
private static int port = 44;
// private static string response;
public event onConnectEventHandler onConnect;
public event onErrorEventHandler onError;
public event onDataArrivalEventHandler onDataArrival;
public event onDisconnectEventHandler onDisconnect;
public event onSendCompleteEventHandler onSendComplete;
public void Connect(string RemoteHostName, int RemotePort)
{
try
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
port = RemotePort;
ipHostInfo = Dns.GetHostEntry(RemoteHostName);
ipAddress = ipHostInfo.AddressList[0];
var remoteEP = new IPEndPoint(ipAddress, port);
client.BeginConnect(remoteEP, sockConnected, client);
}
catch (Exception ex)
{
if (onError != null)
onError(ex.Message);
return;
}
}
public void SendData(byte[] Data)
{
try
{
var byteData = Data;
client.BeginSend(byteData, 0, byteData.Length, 0, sockSendEnd, client);
}
catch (Exception ex)
{
if (onError != null)
onError(ex.Message);
return;
}
}
public void Disconnect()
{
try
{
client.Shutdown(SocketShutdown.Both);
}
catch
{
}
onDisconnect();
client.Close();
}
public byte[] StringToBytes(string Data)
{
return Encoding.ASCII.GetBytes(Data);
}
public string BytestoString(byte[] Data)
{
return Encoding.ASCII.GetString(Data);
}
private void sockConnected(IAsyncResult ar)
{
try
{
if (client.Connected == false)
{
if (onError != null)
onError(”Connection refused.”);
return;
}
var state = new StateObject();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, state.BufferSize, 0, sockDataArrival, state);
if (onConnect != null)
onConnect();
}
catch (Exception ex)
{
if (onError != null)
onError(ex.Message);
return;
}
}
private void sockDataArrival(IAsyncResult ar)
{
var state = (StateObject)ar.AsyncState;
var client = state.workSocket;
var bytesRead = 0;
try
{
bytesRead = client.EndReceive(ar);
}
catch
{
return;
}
try
{
var Data = state.buffer;
if (bytesRead == 0)
{
client.Shutdown(SocketShutdown.Both);
client.Close();
if (onDisconnect != null)
onDisconnect();
return;
}
state.buffer = new byte[32768];
client.BeginReceive(state.buffer, 0, state.BufferSize, 0, sockDataArrival, state);
if (onDataArrival != null)
onDataArrival(Data, bytesRead);
}
catch (Exception ex)
{
if (onError != null)
onError(ex.Message);
return;
}
}
private void sockSendEnd(IAsyncResult ar)
{
try
{
var client = (Socket)ar.AsyncState;
var bytesSent = client.EndSend(ar);
if (onSendComplete != null)
onSendComplete(bytesSent);
}
catch (Exception ex)
{
if (onError != null)
onError(ex.Message);
return;
}
}
public bool Connected()
{
try
{
return client.Connected;
}
catch (Exception ex)
{
if (onError != null)
onError(ex.Message);
return false;
}
}
}
    /*
     * Sockets Class
     * (C)2009 Daniel Moss
     *
     * Handles all of the Socket functions
     * DO NOT REMOVE (C) NOTICE!
     *
     */

    internal class StateObject
    {
        public byte[] buffer = new byte[32768];
        public int BufferSize = 32767;
        public StringBuilder sb = new StringBuilder();
        public Socket workSocket;
    }

    internal class SocketsClass
    {
        #region Delegates

        public delegate void onConnectEventHandler();

        public delegate void onDataArrivalEventHandler(byte[] Data, int TotalBytes);

        public delegate void onDisconnectEventHandler();

        public delegate void onErrorEventHandler(string Description);

        public delegate void onSendCompleteEventHandler(int DataSize);

        #endregion

        private static Socket  client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private static IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");
        private static IPAddress ipAddress = ipHostInfo.AddressList[0];
        private static int port = 44;
       // private static string response;
        public event onConnectEventHandler onConnect;

        public event onErrorEventHandler onError;

        public event onDataArrivalEventHandler onDataArrival;

        public event onDisconnectEventHandler onDisconnect;

        public event onSendCompleteEventHandler onSendComplete;

        public void Connect(string RemoteHostName, int RemotePort)
        {
            try
            {
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                port = RemotePort;
                ipHostInfo = Dns.GetHostEntry(RemoteHostName);
                ipAddress = ipHostInfo.AddressList[0];
                var remoteEP = new IPEndPoint(ipAddress, port);
                client.BeginConnect(remoteEP, sockConnected, client);
            }
            catch (Exception ex)
            {
                if (onError != null)

                    onError(ex.Message);
                return;
            }
        }

        public void SendData(byte[] Data)
        {
            try
            {
                var byteData = Data;
                client.BeginSend(byteData, 0, byteData.Length, 0, sockSendEnd, client);
            }
            catch (Exception ex)
            {
                if (onError != null)

                    onError(ex.Message);
                return;
            }
        }

        public void Disconnect()
        {
            try
            {

                client.Shutdown(SocketShutdown.Both);
            }
            catch
            {
            }
            onDisconnect();
            client.Close();
        }

        public byte[] StringToBytes(string Data)
        {
            return Encoding.ASCII.GetBytes(Data);
        }

        public string BytestoString(byte[] Data)
        {
            return Encoding.ASCII.GetString(Data);
        }

        private void sockConnected(IAsyncResult ar)
        {
            try
            {
                if (client.Connected == false)
                {
                    if (onError != null)
                        onError("Connection refused.");
                    return;
                }
                var state = new StateObject();
                state.workSocket = client;
                client.BeginReceive(state.buffer, 0, state.BufferSize, 0, sockDataArrival, state);
                if (onConnect != null)
                    onConnect();
            }
            catch (Exception ex)
            {
                if (onError != null)

                    onError(ex.Message);
                return;
            }
        }

        private void sockDataArrival(IAsyncResult ar)
        {
            var state = (StateObject)ar.AsyncState;
            var client = state.workSocket;
            var bytesRead = 0;

            try
            {
                bytesRead = client.EndReceive(ar);
            }
            catch
            {
                return;
            }

            try
            {
                var Data = state.buffer;
                if (bytesRead == 0)
                {
                    client.Shutdown(SocketShutdown.Both);
                    client.Close();
                    if (onDisconnect != null)
                        onDisconnect();
                    return;
                }
                state.buffer = new byte[32768];

                client.BeginReceive(state.buffer, 0, state.BufferSize, 0, sockDataArrival, state);
                if (onDataArrival != null)
                    onDataArrival(Data, bytesRead);
            }
            catch (Exception ex)
            {
                if (onError != null)

                    onError(ex.Message);
                return;
            }
        }

        private void sockSendEnd(IAsyncResult ar)
        {
            try
            {
                var client = (Socket)ar.AsyncState;
                var bytesSent = client.EndSend(ar);
                if (onSendComplete != null)
                    onSendComplete(bytesSent);
            }
            catch (Exception ex)
            {
                if (onError != null)

                    onError(ex.Message);
                return;
            }
        }

        public bool Connected()
        {
            try
            {
                return client.Connected;
            }
            catch (Exception ex)
            {
                if (onError != null)

                    onError(ex.Message);
                return false;
            }
        }
    }

private SocketsClass pClient = new SocketsClass ();

You can then use event handlers such as:

pClient.onConnect += this.Client_onConnect;

pClient.onDataArrival += this.Client_onDataArrival;

pClient.onError += this.Client_onError;

pClient.onDisconnect += this.Client_onDisconnect;

pClient.onSendComplete +=this.Client_onSendComplete;

Hope this is useful to people ;)

Took me ages to work this out

RSS Feed

44 Comments for C# – Easy Sockets Class

fvjplalqnl | December 2, 2009 at 3:06 AM

i3RlUo knhojcsommms, [url=http://fuqbnvyorslq.com/]fuqbnvyorslq[/url], [link=http://mrpkoeotqwob.com/]mrpkoeotqwob[/link], http://ypwritsljxel.com/

fxxtzlqbobv | January 12, 2010 at 8:36 PM

HLdqBi ysmvrlbfwlej, [url=http://tuvfsgsxytgc.com/]tuvfsgsxytgc[/url], [link=http://dcawhklbciri.com/]dcawhklbciri[/link], http://repbcdbesdsu.com/

small | January 15, 2010 at 5:40 AM

propecia >:[[ soma 8-DDD viagra 94064 levitra 6174

wentylacja | January 15, 2010 at 7:43 PM

buy cialis online hsnvjt viagra =-D accutane >:-(( cialis oahcd

alexander | January 17, 2010 at 3:14 PM

valium 1949 cialis mapz viagra 2140 cialis 8-) auto insurance sldda

rynny2 | January 24, 2010 at 11:03 PM

home insurance lkdt auto insurance aiad car insurance ryq car insurance %] cheap auto insurance :-OO

verdananormal | January 26, 2010 at 2:30 AM

home insurance 8( health insurance =) life insurance %[ car insurance quotes tfuddi cheap auto insurance 642

Buhric | January 28, 2010 at 6:57 PM

phentermine online >:[

arialnormal | January 31, 2010 at 4:53 AM

buy phentermine >:]]

trullchen321 | February 1, 2010 at 7:11 PM

home insurance ccnqvj auto insurance qijev car insurance 908047

irena | February 2, 2010 at 9:57 PM

auto insurance bmcr auto insurance zmc cheap auto insurance 38752 auto insurance %[[

metallsp | February 3, 2010 at 8:42 PM

health insurance 5307 individual health insurance plans 99486 whole life insurance policies 464

smalltext | February 4, 2010 at 4:25 PM

home insurance 8-[[ life insurance hmjnk children health insurance %)) new york car insurance tky

nospy | February 5, 2010 at 11:55 PM

nasacort aciphex phentermine pharmacy pittsburgh fafzi accutane phcu nasacort aciphex phentermine actos imitrex >:-OOO propecia %-DD order phentermine pej

internelink | February 6, 2010 at 12:22 AM

buy valium online no 06155 tramadol propecia dlk xanax 8]] generic brands for ultram 8255 levitra =P

brennan | February 7, 2010 at 4:20 PM

buy tramadol %-((( accutane ycxenj accutane :D D phentermine hcl 8-PP buy cialis 0559 2003 cialis levitra market sales viagra :-P viagra 8DD

inhoudsopave | February 7, 2010 at 5:54 PM

diet pills phentermine 10008 tramadol loftj xanax 613 buy cialis 3957 valium 867115 valium :-D D xanax pfd levitra %-]]

risik0o9 | February 8, 2010 at 6:32 PM

xanax no prescription >:DDD ambien :-]]] health insurance kpve accutane uhifwg health insurance =-(( temporary health insurance ihjslp

stonecreek | February 8, 2010 at 9:24 PM

cheap prices on cialis =-((( auto insurance 5939 xanax and grapefruit 8) propecia 8371 accutane =-P online pharmacy ultram mozilla 43847 buy levitra online :O car insurance online 50919

eurycantha | February 9, 2010 at 11:48 PM

get rx for tramadol online npoeno no exam life insurance :-[ buy tramadol without priscription 286308 ultram 48505 levitra =-[[[ health insurance 56521 ultram %(((

dieter | February 10, 2010 at 1:46 AM

buy phentermine 342 accutane 4957 buy phentermine xtff xanax 65601 personal health insurance bfbwz car insurance niew

tatiana | February 10, 2010 at 6:33 AM

accutane 601 tramadol online lowest price 33868 buy tramadol gpjk

ruttger | February 10, 2010 at 8:58 AM

ambien 8-(( aciphex tjrt phentermine xqdx

twitterusername | February 11, 2010 at 7:59 PM

online casino nfgo private health insurance 4660 health insurance online ekb home insurance =[

Luffie | February 22, 2010 at 8:54 AM

I just got a new laptop for christmas. I want to download limewire so i can get free music but i heard that it can get viruses. Is this true because i dont want a virus on my new laptop? ps. Its not a mac santoramaa

Pharmb77 | March 1, 2010 at 1:51 PM

Hello! gkfecfk interesting gkfecfk site!

Pharmd188 | March 1, 2010 at 1:52 PM

Very nice site! cheap viagra

Pharmk977 | March 1, 2010 at 1:52 PM

Very nice site! [url=http://apeoixy.com/xqqass/2.html]cheap cialis[/url]

Pharma302 | March 1, 2010 at 1:52 PM

Very nice site! cheap cialis http://apeoixy.com/xqqass/4.html

Pharmc405 | March 1, 2010 at 1:52 PM

Very nice site!

Pharmd640 | March 1, 2010 at 1:52 PM

xanax | March 3, 2010 at 11:05 PM

ivagra | March 4, 2010 at 3:35 PM

bannerwelcome | March 5, 2010 at 3:00 AM

xanax xqgi aciphex 8] carisoprodol vunxaf tramadol wpv

wizardcontainer | March 5, 2010 at 6:51 AM

generic valium 8[[[ tramadol 26010 ambien problems hrejp doxycycline ude

cialis | March 5, 2010 at 11:28 AM

alena | March 5, 2010 at 9:31 PM

xanax online zgpb doxycycline 980 lowest prices for tramadol online %-PP carisoprodol nqngfb

designerlampe | March 6, 2010 at 12:40 AM

acomplia 54223 retin a vazt buy xanax vtk cheap drug retin tramadol viagra 32510 accutane >:-DDD

vs | March 6, 2010 at 1:12 PM

xanax | March 6, 2010 at 8:25 PM

Hello!
xanax , tramadol , viagra , xanax , cialis ,

colorado | March 8, 2010 at 4:57 AM

ambien sleep eating 69187 doxycycline tailw retin dksyb propecia results %-PP

phentermine | March 8, 2010 at 7:33 PM

cheapest_cialis | March 9, 2010 at 11:18 AM

bernard | March 9, 2010 at 10:32 PM

tramadol 8-((( tramadol =-]]] aciphex ypm ultram pain pill >:(((

Leave a comment!

« C# – Configure Proxy for Webclient

Car is back on Road, Taxed and MOT’d »

Find it!

Theme Design by devolux.org

Tag Cloud