Advertisement
Guest User

Untitled

a guest
Jul 30th, 2014
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.17 KB | None | 0 0
  1. class Program
  2. {
  3.     private static ClientWebSocket socket;
  4.  
  5.     static void Main(string[] args)
  6.     {
  7.         Task.WaitAll(run());
  8.     }
  9.  
  10.     static async Task run()
  11.     {
  12.         Console.WriteLine("Running. Press Ctrl-C to exit.");
  13.  
  14.         await connect(new Uri("ws://echo.websocket.org"));
  15.  
  16.         while (true)
  17.         {
  18.             await take_input();
  19.         }
  20.     }
  21.  
  22.     static async Task connect(Uri uri)
  23.     {
  24.         Console.WriteLine("Connecting to: {0}", uri);
  25.  
  26.         socket = new ClientWebSocket();
  27.  
  28.         await socket.ConnectAsync(uri, CancellationToken.None);
  29.     }
  30.  
  31.     static async Task take_input()
  32.     {
  33.         Console.Write("Input: ");
  34.  
  35.         await send(socket, Console.ReadLine());
  36.  
  37.         Console.WriteLine("Response: {0}", await receive(socket));
  38.     }
  39.  
  40.     static async Task send(ClientWebSocket socket, string value)
  41.     {
  42.         await socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(value)), WebSocketMessageType.Text, true, CancellationToken.None);
  43.     }
  44.  
  45.     static async Task<string> receive(ClientWebSocket socket)
  46.     {
  47.         var buffer = new ArraySegment<byte>(new byte[1024]);
  48.         var response = await socket.ReceiveAsync(buffer, CancellationToken.None);
  49.         return Encoding.UTF8.GetString(buffer.Array.Take(response.Count).ToArray());
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement