Created
August 7, 2015 12:43
-
-
Save Deathspike/e726c8b50c8de607cc46 to your computer and use it in GitHub Desktop.
Super simple and super naive threaded socket server with async/await
This file contains hidden or 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.IO; | |
using System.Net; | |
using System.Net.Sockets; | |
using System.Threading.Tasks; | |
namespace Test { | |
internal class Program { | |
public static void Main() { | |
var client = Task.Run(() => Client()); | |
var server = Task.Run(() => Server()); | |
Task.WaitAll(client, server); | |
} | |
public static async Task Client() { | |
await Task.Delay(1000); | |
using (var client = new TcpClient()) { | |
await client.ConnectAsync("localhost", 8080); | |
using (var stream = client.GetStream()) | |
using (var reader = new StreamReader(stream)) | |
using (var writer = new StreamWriter(stream)) { | |
var line = await reader.ReadLineAsync(); | |
Console.WriteLine("Client: Message from server: {0}", line); | |
await writer.WriteLineAsync(line); | |
await writer.FlushAsync(); | |
} | |
} | |
} | |
public static async Task Server() { | |
var listener = new TcpListener(IPAddress.Any, 8080); | |
listener.Start(); | |
while (true) { | |
var client = await listener.AcceptTcpClientAsync(); | |
Task.Run(() => ServerForClient(client)); | |
} | |
} | |
public static async Task ServerForClient(TcpClient client) { | |
using (client) | |
using (var stream = client.GetStream()) | |
using (var reader = new StreamReader(stream)) | |
using (var writer = new StreamWriter(stream)) { | |
await writer.WriteLineAsync("Hello client!"); | |
await writer.FlushAsync(); | |
var line = await reader.ReadLineAsync(); | |
Console.WriteLine("Server: Message from client: {0}", line); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment