Skip to content

Instantly share code, notes, and snippets.

@PaulStovell
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PaulStovell/a58cd48a5c6b14885cf3 to your computer and use it in GitHub Desktop.
Save PaulStovell/a58cd48a5c6b14885cf3 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ClientServer
{
class Program
{
private static TcpListener listener;
static void Main(string[] args)
{
ThreadPool.SetMinThreads(20, 20);
StartListener();
var watch = Stopwatch.StartNew();
for (var i = 0; i < 20; i++)
{
ExecuteClient();
}
Console.WriteLine("20 clients in: " + watch.ElapsedMilliseconds + "ms");
Console.WriteLine("Hit Enter to quit");
Console.ReadLine();
listener.Stop();
}
private static void StartListener()
{
listener = new TcpListener(new IPEndPoint(IPAddress.Any, 8012));
listener.Start();
AcceptLoop();
}
private static void AcceptLoop()
{
listener.BeginAcceptTcpClient(ar =>
{
var tcpClient = listener.EndAcceptTcpClient(ar);
ThreadPool.QueueUserWorkItem(delegate
{
HandleIncomingClientRequestOnThread(tcpClient);
});
AcceptLoop();
}, null);
}
private static void HandleIncomingClientRequestOnThread(TcpClient tcpClient)
{
var stream = tcpClient.GetStream();
ReadSomeData(stream);
WriteSomeData(stream);
tcpClient.Close();
}
private static void ExecuteClient()
{
using (var client = new TcpClient())
{
client.Connect("localhost", 8012);
using (var stream = client.GetStream())
{
WriteSomeData(stream);
ReadSomeData(stream);
}
}
}
static void WriteSomeData(NetworkStream stream)
{
var buffer = new byte[50];
new Random().NextBytes(buffer);
stream.Write(buffer, 0, 50);
}
static void ReadSomeData(NetworkStream stream)
{
var buffer = new byte[50];
var read = stream.Read(buffer, 0, buffer.Length);
Debug.Assert(read == 50);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment