tom_burgess

TCPEchoClient

Apr 7th, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.87 KB | None | 0 0
  1. using System;
  2. using System.Text;
  3. using System.IO;
  4. using System.Net.Sockets;
  5.  
  6. class TcpEchoClient
  7. {
  8.     static void Main(string[] args)
  9.     {
  10.         if ((args.Length < 2 || args.Length > 3))
  11.             throw new ArgumentException("Parameters: <server> <word> (<port>)");
  12.  
  13.         string server = args[0]; // read the server's name from the first argument of the console's input stream
  14.  
  15.         byte[] byteBuffer = Encoding.ASCII.GetBytes(args[1]); // get the echo data from console's input stream
  16.  
  17.         int serverPort = (args.Length == 3) ? Int32.Parse(args[2]) : 7;
  18.  
  19.         TcpClient client = null; // variable to hold the socket
  20.         NetworkStream netStream = null; // allows data to be sent
  21.  
  22.         try
  23.         {
  24.             client = new TcpClient(server, serverPort);
  25.  
  26.             Console.WriteLine("Connected to server.. sending echo string");
  27.  
  28.             netStream = client.GetStream();
  29.             netStream.Write(byteBuffer, 0, byteBuffer.Length); // send string to echo server
  30.  
  31.             Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);
  32.  
  33.             int totalBytesRcvd = 0;
  34.             int bytesRcvd = 0;
  35.  
  36.             while (totalBytesRcvd < byteBuffer.Length)
  37.             {
  38.                 // repeatedly recieve bytes until it's same number as amount sent
  39.                 if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd, byteBuffer.Length - totalBytesRcvd)) == 0)
  40.                 { // remember read does nothing until some data is available
  41.                     Console.WriteLine("Connection closed prematurely.");
  42.                     break;
  43.                 }
  44.                 totalBytesRcvd += bytesRcvd;
  45.             }
  46.         }catch(Exception e)
  47.         {
  48.             Console.WriteLine(e.Message);
  49.         }
  50.         finally
  51.         {
  52.             netStream.Close();
  53.             client.Close();
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment