Hack Forums
[.NET] Event based socket object - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [.NET] Event based socket object (/showthread.php?tid=5735967)



Event based socket object - Ninja - Oct 12, 2017

Just a little wrapper I made for the Socket object to add easier to use asynchronous methods to it along with events. You can find the gist here:
https://gist.github.com/GekkeVent/d9ed6a8e2ef03fe785357a4973271f34

Usage:
Code
AsyncSocket socket = new AsyncSocket();
socket.SocketConnected += (s, e) => Console.WriteLine("Connected!");
socket.DataSent += (s, e) => Console.WriteLine("Data sent!");
socket.DataReceived += (s, e) =>
{
    byte[] buffer = e.Buffers[0].Array;
    object state = e.State;
    Console.WriteLine(Encoding.ASCII.GetString(buffer));
}
socket.SocketDisconnected += (s, e) => Console.WriteLine("Disconnected!");

The ConnectAsync, SendAsync, ReceiveAsync, and DisconnectAsync methods all have the same parameters as their non-async equivalent and thus can be used the same way. I did not add awaitable support, since people can do that themselves using the Begin<method> methods and get the AsyncWaitHandle from the IAsyncResult themselves. It does support a state object. The events only work for the Async methods, I did not overload the standard methods.


* - Xogg - Oct 12, 2017

Have to say, If I were to every use socket in .NET I would use this wrapper :D

Just because the events honestly LOL


* - Ninja - Oct 12, 2017

(Oct 12, 2017 06:41 PM)Dexuh Wrote:  Have to say, If I were to every use socket in .NET I would use this wrapper :D

Just because the events honestly LOL

Thanks. I remember your post about Delphi sockets in the C# section. Sockets can actually be really easy in .NET, you just have to add a few features yourself. Here is an older project that shows what you can accomplish with sockets in .NET:
https://hackforums.net/showthread.php?tid=5618361


* - +Haze - Oct 13, 2017

I like the abstraction and how simple it looks.


* - Ninja - Oct 13, 2017

(Oct 13, 2017 10:45 AM)+Haze Wrote:  I like the abstraction and how simple it looks.

Simple, yet effective.


Added state object support.


* - gigajew - Oct 13, 2017

Add GetStream() easily by returning new NetworkStream(Socket socket); nice job on this Ninja. You may be Jew material after all


* - Ninja - Oct 14, 2017

(Oct 13, 2017 09:41 PM)gigajew Wrote:  Add GetStream() easily by returning new NetworkStream(Socket socket); nice job on this Ninja. You may be Jew material after all

This was just an abstraction to add events. If you want to more easily use sockets then use this:
https://hackforums.net/showthread.php?tid=5618361
It features timeouts, easier to use send/receive methods, and more.