How do I use SimplSockets with a delegate for a “h

2019-04-19 01:36发布

问题:

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.

回答1:

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();
    }
}