Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use SimplSockets with a delegate for a "hello world" project?

I’m looking into the SimplSockets library for building an application that uses sockets. However, after checking other questions on Stack Overflow, the author’s blog, the source, and several Internet searches, I can’t find a straightforward way to create a “hello world” project using SimplSockets.

How do I create a “hello world” application that uses SimplSockets?

To prevent a "too broad" closure, all I want to do is send and receive some data. A string, whatever. The reason I opened this question is because I'm unsure on how to call the constructor since it uses func<T> where T is a socket.

like image 432
makerofthings7 Avatar asked Aug 01 '14 19:08

makerofthings7


1 Answers

The issue I had with SimplSockets is that I didn’t properly understand how to use the delegate needed in the constructor.

Below is a sample client/server that echoes the data typed back at you. I have no idea what I should be doing instead of Thread.Sleep(), so I’ll leave that there unless someone has a better suggestion.

private static void ConnectUsingSimpleSockets()
{
    int maxClients = 50;
    int maxPeers = 10;

    var socketCreator = () => new System.Net.Sockets.Socket(SocketType.Stream, ProtocolType.Tcp);

    using (var client = new SimplSockets.SimplSocket(socketCreator, 5000, 10, true))
    {
        client.MessageReceived += client_MessageReceived;
        client.Error += client_Error;

        var ss = new System.Net.IPEndPoint(BitConverter.ToInt32(IPAddress.Parse("127.0.0.1").GetAddressBytes(), 0), 4747);
        if (client.Connect(ss))
        {
            Console.WriteLine("type something..");
            while (true)
            {
                string resul = Console.ReadLine();

                byte[] data = client.SendReceive(UTF8Encoding.UTF8.GetBytes("Client Send: " + resul + DateTime.Now));

                if (data == UTF8Encoding.UTF8.GetBytes("END"))
                {
                    break;
                }
                Console.WriteLine(UTF8Encoding.UTF8.GetString(data));

            }
        }
        client.Close();


        client.Listen(ss);
        while (true)
        {
            Console.WriteLine("sleeping");
            Thread.Sleep(7000);
        }
        client.Close();
    }
}
like image 118
makerofthings7 Avatar answered Oct 24 '22 03:10

makerofthings7