Skip to content

Latest commit

Β 

History

History
289 lines (248 loc) Β· 8.46 KB

README.md

File metadata and controls

289 lines (248 loc) Β· 8.46 KB

logo

SimpleTcp

Hits MIT license Nuget version Nuget downloads GitHub starts

A simple-to-use TCP server and client library.

🎨 Features

  • Asynchronous servers and clients that are very easy to use.
  • PacketTcpServer that ensures reception without truncating the size of the data sent.
  • HTTP server that is very simple to use.

πŸ“ƒ Usage

Start Tcp Server

RawTcpServer tcpServer = new RawTcpServer();
tcpServer.Start(5000);

Can use Event Handlers

RawTcpServer tcpServer = new RawTcpServer();
tcpServer.ClientConnected += ClientConnected;
tcpServer.ClientDisconnected += ClientDisconnected;
tcpServer.DataReceived += DataReceived;

Get connected clinets

tcpServer.Clients

Send data to client

tcpServer.Clients[0].Write(buffer, 0, buffer.Length);

Send data to connected all clients

tcpServer.WriteToAllClients(buffer, 0, buffer.Length);

Connect to Tcp Server

RawTcpClient tcpClient = new RawTcpClient();
tcpClient.Connect("127.0.0.1", 5000);

Can use Event Handlers

RawTcpClient tcpClient = new RawTcpClient();
tcpClient.Connected += Connected;
tcpClient.Disconnected += Disconnected;
tcpClient.DataReceived += DataReceived;

Send data to server

tcpClient.Write(buffer, 0, buffer.Length);

Start Simple Http Server

See the example project for details.

HttpServer httpServer = new HttpServer();
httpServer.HttpRequest += (sender, e) =>
{
    return new HttpResponse(HttpStatusCode.OK); 
};
httpServer.Start(); // default start port is 80

🐾 Examples

Echo Server / Client

Echo Server

static void Main(string[] args)
{
    using (RawTcpServer tcpServer = new RawTcpServer())
    {
        tcpServer.ClientConnected += (sender, e) =>
            Console.WriteLine($"[{e}]: Connected"); // new client connected
        tcpServer.ClientDisconnected += (sender, e) =>
            Console.WriteLine($"[{e}]: Disconnected"); // client disconnected
        tcpServer.DataReceived += (sender, e) =>
        {
            byte[] readBytes = e.Client.ReadExisting(); // read all data
            string dataString = readBytes.Aggregate( // data to hex string
                new StringBuilder(32),
                (stringBuilder, data) => stringBuilder.Append($" 0x{data.ToString("X2")}")
                ).ToString().Trim();

            Console.WriteLine($"[{e.Client}]: {dataString}");

            e.Client.Write(readBytes, 0, readBytes.Length); // return same data
        };

        try
        {
            tcpServer.Start(5000);
            Console.WriteLine("Listening for connections...");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

        Console.ReadLine();
    }
}

Echo Client

static void Main(string[] args)
{
    using (RawTcpClient tcpClient = new RawTcpClient())
    {
        tcpClient.Connected += (sender, e) =>
            Console.WriteLine($"Connect to [{e.RemoteEndPoint}]");
        tcpClient.Disconnected += (sender, e) =>
            Console.WriteLine($"{Environment.NewLine}Disconnected from [{e.RemoteEndPoint}]");
        tcpClient.DataReceived += (sender, e) =>
        {
            if (sender is RawTcpClient rawTcpClient)
            {
                byte[] readBytes = rawTcpClient.ReadExisting(); // read all data
                Console.WriteLine($"DataReceived: {Encoding.ASCII.GetString(readBytes)}");
            }
        };

        try
        {
            tcpClient.Connect("127.0.0.1", 5000);

            while (true)
            {
                string line = Console.ReadLine();
                byte[] buffer = Encoding.ASCII.GetBytes(line);
                tcpClient.Write(buffer, 0, buffer.Length);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            Console.ReadLine();
        }
    }
}
Packet Echo Server / Client

Packet Echo Server

The size of the received data is received without being cut off.

static void Main(string[] args)
{
  using (PacketTcpServer tcpServer = new PacketTcpServer())
  {
      tcpServer.ClientConnected += (sender, e) =>
          Console.WriteLine($"[{e}]: Connected"); // new client connected
      tcpServer.ClientDisconnected += (sender, e) =>
          Console.WriteLine($"[{e}]: Disconnected"); // client disconnected
      tcpServer.PacketReceived += (sender, e) =>
      {
          if (sender is PacketTcpServer packetTcpServer)
          {
              Console.WriteLine($"[{e.Packet.IPEndPoint}]: PacketReceived (PacketLength: {e.Packet.PacketData.Length})");
              packetTcpServer.WritePacket(e.Packet.TcpClient, e.Packet.PacketData); // return same packet
          }
      };

      try
      {
          tcpServer.Start(5000);
          Console.WriteLine("Listening for connections...");
      }
      catch (Exception ex)
      {
          Console.WriteLine(ex);
      }

      Console.ReadLine();
  }
}

Packet Echo Client

static void Main(string[] args)
{
    using (PacketTcpClient tcpClient = new PacketTcpClient())
    {
        tcpClient.Connected += (sender, e) =>
            Console.WriteLine($"Connect to [{e.RemoteEndPoint}]");
        tcpClient.Disconnected += (sender, e) =>
            Console.WriteLine($"{Environment.NewLine}Disconnected from [{e.RemoteEndPoint}]");
        tcpClient.PacketReceived += (sender, e) =>
        {
            Console.WriteLine($"PacketReceived: (PacketLength: {e.PacketData.Length})");
        };

        try
        {
            tcpClient.Connect("127.0.0.1", 5000);

            tcpClient.WritePacket(new byte[1024]); // send 1024 bytes
            tcpClient.WritePacket(new byte[1024 * 1024]); // send 1024 * 1024 bytes
            tcpClient.WritePacket(new byte[1024 * 1024 * 10]); // send 1024 * 1024 * 10 bytes

            Console.ReadLine();

            tcpClient.Disconnect();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

        Console.ReadLine();
    }
}

image

Http Server

Simple Http Server

static void Main(string[] args)
{
    using (var httpServer = new SimpleTcp.Server.Http.HttpServer())
    {
        httpServer.HttpRequest += (sender, e) =>
        {
            Console.WriteLine($"[{e.Request.IPEndPoint}] -> [{e.Request.Url}]");
            switch(e.Request.Url)
            {
                case "/":
                    return new HttpResponse(HttpStatusCode.OK)
                    {
                        Content = Encoding.UTF8.GetBytes(
                            "<!DOCTYPE html>" +
                            "<html>" +
                            "<head>" +
                            "<meta charset=\"UTF-8\">" +
                            "<title>SimpleTcp HttpServer Example</title>" +
                            "</head>" +
                            "<body>" +
                            "Hello, World !!<br/><a href=\"https://github.com/akon47/SimpleTcp\">Github</a>" +
                            "</body>" +
                            "</html>")
                    };
                default:
                    return new HttpResponse(HttpStatusCode.NotFound);
            }
        };
        httpServer.Start();

        Console.ReadLine();
    }
}

image

🐞 Bug Report

If you find a bug, please report to us posting issues on GitHub.