Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Text;
- using System.IO;
- using System.Net.Sockets;
- class TcpEchoClient
- {
- static void Main(string[] args)
- {
- if ((args.Length < 2 || args.Length > 3))
- throw new ArgumentException("Parameters: <server> <word> (<port>)");
- string server = args[0]; // read the server's name from the first argument of the console's input stream
- byte[] byteBuffer = Encoding.ASCII.GetBytes(args[1]); // get the echo data from console's input stream
- int serverPort = (args.Length == 3) ? Int32.Parse(args[2]) : 7;
- TcpClient client = null; // variable to hold the socket
- NetworkStream netStream = null; // allows data to be sent
- try
- {
- client = new TcpClient(server, serverPort);
- Console.WriteLine("Connected to server.. sending echo string");
- netStream = client.GetStream();
- netStream.Write(byteBuffer, 0, byteBuffer.Length); // send string to echo server
- Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);
- int totalBytesRcvd = 0;
- int bytesRcvd = 0;
- while (totalBytesRcvd < byteBuffer.Length)
- {
- // repeatedly recieve bytes until it's same number as amount sent
- if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd, byteBuffer.Length - totalBytesRcvd)) == 0)
- { // remember read does nothing until some data is available
- Console.WriteLine("Connection closed prematurely.");
- break;
- }
- totalBytesRcvd += bytesRcvd;
- }
- }catch(Exception e)
- {
- Console.WriteLine(e.Message);
- }
- finally
- {
- netStream.Close();
- client.Close();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment