Network I/O

Just as with input, network output can use Socket, Stream, or WebRequest objects. The basic unit of network communication is the Socket. For higher-level network output, you can use the WebRequest class. Whether communicating over a Socket or a WebRequest, however, you’ll be using a Stream to actually read and write data.

Writing data with Sockets

To communicate over a network using a Socket, there must be a server of some sort listening for requests at the other end. The construction of network application servers is beyond the scope of this book, but Example 3-1 shows you how to create a simple network client program.

Example 3-1. A simple network client program
using System;
using System.IO;
using System.Net.Sockets;

public class NetWriter {

  public static void Main(string [ ] args) {

    string address = "example.com";
    int port = 9999;

    TcpClient client = new TcpClient(address,port);
    NetworkStream stream = client.GetStream( );

    StreamWriter writer = new StreamWriter(stream);

    writer.WriteLine("hello\r\n");
    writer.Flush( );

    using (StreamReader reader = new StreamReader(stream)) {
      while (reader.Peek( ) != -1) {
        Console.WriteLine(reader.ReadLine( ));
      }
    }
  }
}

The Main( ) method can be broken down into its major steps. The first step is to initialize some variables:

string address = "example.com";
int port = 9999;

TcpClient is a convenient specialization of a TCP/IP client Socket. The GetStream( ) method makes the connection and returns a Stream to communicate with the remote ...

Get .NET & XML now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.