-
-
Save PaulStovell/a58cd48a5c6b14885cf3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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