Created
July 22, 2013 18:19
-
-
Save joaoportela/6056200 to your computer and use it in GitHub Desktop.
Very simple experiment with C# Tasks and async + await. Do not take any of this code as correct or even as best practice. I'm just trying to understand how this all works. 1st obvious shortcomming: The server only accepts one client connection at a time.
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.IO; | |
using System.Linq; | |
using System.Net.Sockets; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Windows; | |
using System.Windows.Controls; | |
using System.Windows.Data; | |
using System.Windows.Documents; | |
using System.Windows.Input; | |
using System.Windows.Media; | |
using System.Windows.Media.Imaging; | |
using System.Windows.Navigation; | |
using System.Windows.Shapes; | |
namespace MyTcpClient | |
{ | |
/// <summary> | |
/// Interaction logic for MainWindow.xaml | |
/// </summary> | |
public partial class MainWindow : Window | |
{ | |
public MainWindow() | |
{ | |
InitializeComponent(); | |
Task _ = ConnectAsTcpClient("127.0.0.1", 1234); | |
} | |
private void OutputWriteLine(string text) | |
{ | |
output.Text = output.Text + "\n" + text; | |
outputScroll.ScrollToEnd(); | |
} | |
private void Button_Click(object sender, RoutedEventArgs e) | |
{ | |
OutputWriteLine("Button_Click"); | |
} | |
private async Task ConnectAsTcpClient(string ip, int port) | |
{ | |
for (; ; ) | |
{ | |
try | |
{ | |
await Task.Delay(millisecondsDelay: 1000); | |
using (var tcpClient = new TcpClient()) | |
{ | |
OutputWriteLine("[Client] Attempting connection to server " + ip + ":" + port); | |
Task connectTask = tcpClient.ConnectAsync(ip, port); | |
Task timeoutTask = Task.Delay(millisecondsDelay: 100); | |
if (await Task.WhenAny(connectTask, timeoutTask) == timeoutTask) | |
{ | |
throw new TimeoutException(); | |
} | |
OutputWriteLine("[Client] Connected to server"); | |
using (var networkStream = tcpClient.GetStream()) | |
using (var reader = new StreamReader(networkStream)) | |
using (var writer = new StreamWriter(networkStream) { AutoFlush = true }) | |
{ | |
OutputWriteLine(string.Format("[Client] Writing request '{0}'", ClientRequestString)); | |
await writer.WriteLineAsync(ClientRequestString); | |
try | |
{ | |
for (; ; ) | |
{ | |
var response = await reader.ReadLineAsync(); | |
if (response == null) { break; } | |
OutputWriteLine(string.Format("[Client] Server response was '{0}'", response)); | |
} | |
OutputWriteLine("[Client] Server disconnected"); | |
} | |
catch (IOException) | |
{ | |
OutputWriteLine("[Client] Server disconnected"); | |
} | |
} | |
} | |
} | |
catch (TimeoutException) | |
{ | |
// reconnect | |
} | |
} | |
} | |
private static readonly string ClientRequestString = "Hello Mr server"; | |
} | |
} |
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.IO; | |
using System.Linq; | |
using System.Net.Sockets; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace MyTcpServer | |
{ | |
class Program | |
{ | |
static int Main(string[] args) | |
{ | |
try | |
{ | |
StartListener(1234).Wait(); | |
return 0; | |
} | |
catch (Exception ex) | |
{ | |
Console.Error.WriteLine(ex); | |
return -1; | |
} | |
} | |
private static async Task StartListener(int port) | |
{ | |
var tcpListener = TcpListener.Create(port); | |
tcpListener.Start(); | |
for (; ; ) | |
{ | |
Console.WriteLine("[Server] waiting for clients..."); | |
using (var tcpClient = await tcpListener.AcceptTcpClientAsync()) | |
{ | |
try | |
{ | |
Console.WriteLine("[Server] Client has connected"); | |
using (var networkStream = tcpClient.GetStream()) | |
using (var reader = new StreamReader(networkStream)) | |
using (var writer = new StreamWriter(networkStream) { AutoFlush = true }) | |
{ | |
var buffer = new byte[4096]; | |
Console.WriteLine("[Server] Reading from client"); | |
var request = await reader.ReadLineAsync(); | |
string.Format(string.Format("[Server] Client wrote '{0}'", request)); | |
for (int i = 0; i < 5; i++) | |
{ | |
await writer.WriteLineAsync("I am the server! HAHAHA!"); | |
Console.WriteLine("[Server] Response has been written"); | |
await Task.Delay(TimeSpan.FromSeconds(1)); | |
} | |
} | |
} | |
catch (Exception) | |
{ | |
Console.WriteLine("[Server] client connection lost"); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Have you been able to use NetworkStream ReadAsync and WriteAsync successfully ? Any examples you could show? Thansks