daily pastebin goal
80%
SHARE
TWEET

Untitled

a guest May 16th, 2018 113 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class SocketClient
  2. {
  3. public ClientSocket() {
  4.     _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  5. }
  6.  
  7. public bool Connect(IPAddress ipAddress, int port) {
  8.     _client.Connect(ipAddress, port);
  9.     if (!_client.Connected) {
  10.         return false;
  11.     }
  12.     Receive();
  13.     return true;
  14. }
  15.  
  16. private async void Receive() {
  17.     var buffer = new byte[4096];
  18.     for (;;) {
  19.         try {
  20.             var bytesRead = await Task.Factory.FromAsync<int>(
  21.                 _client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, null, _client),
  22.                 _client.EndReceive);
  23.             if (bytesRead <= 0) continue;
  24.  
  25.             var message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
  26.             Console.WriteLine(message);
  27.         } catch {
  28.             break;
  29.         }
  30.     }
  31. }
RAW Paste Data
Top