Home   Cover Cover Cover Cover
 

Network communication

Example "EchoServer and EchoClient"

We now wish to implement an echo server as an example. It will receive data and return it unchanged to the sender. To simplify matters, the echo server and also its clients can run on the local computer. Therefore the local address of the computer is given. It is known as loopback address (IPAddress.Loopback). To run the example on different computers only the loopback address needs to be changed to the other IP address. The echo server is kept very simple and so can only serve one client at a time because the connection is closed after each data transfer.

/book/samples/4/Netzwerkkommunikation/EchoServer.cs
using System; 
using System.Net; 
using System.Net.Sockets;

class EchoServer {
  Socket s;
  public bool StartUp(IPAddress ip, int port) {
    try {
      s = new Socket(  AddressFamily.InterNetwork, SocketType.Stream,
        ProtocolType.Tcp);
      s.Bind(new IPEndPoint(ip, port));
      s.Listen(10); 
    } catch (Exception e) {
      Console.WriteLine(e.Message);
      return false;
    }
    for(;;) {
      Socket newSocket = s.Accept(); // blocks until a client connects
      Communicate(newSocket);
    }
  }
  void Communicate(Socket clSock) {
    try {
      byte[] buffer = new byte[1024];
      while (clSock.Receive(buffer) > 0) // Receive blocks until data arrives
        clSock.Send(buffer);
      clSock.Shutdown(SocketShutdown.Both);
      clSock.Close ();
    } catch (Exception e) {
      Console.WriteLine(e.Message);
    }
  }
  public static void Main() {
    EchoServer server = new EchoServer( );
    if (! server.StartUp(IPAddress.Loopback, 50000))
      Console.WriteLine("Starting echo server failed");
  }
}
/book/samples/4/Netzwerkkommunikation/EchoClient.cs
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
class EchoClient {
  public static void Main() {
    try {
      //----- establish connection
      Socket s = new Socket(  AddressFamily.InterNetwork, SocketType.Stream,
        ProtocolType.Tcp);
      s.Connect(new IPEndPoint(IPAddress.Loopback, 50000));
      //----- send
      byte[] msg = Encoding.ASCII.GetBytes("This is a test.");
      s.Send(msg);
      //----- receive
      byte[] retMsg = new byte[1024];
      s.Receive(retMsg);
      string str = Encoding.ASCII.GetString(retMsg);
      Console.WriteLine(str);
    } catch (Exception e) {
      Console.WriteLine(e.Message);
    }
  }
}




Example "WebRequest"

In the following example an HTML file is requested and output on the console:

/book/samples/4/Netzwerkkommunikation/WebRequest.cs
using System; 
using System.IO;  // for StreamReader
using System.Net;  // for WebRequest, WebResponse
class WebTest {
  static void Main() {
    WebRequest request = WebRequest.Create("http://dotnet.jku.at");
    WebResponse response = request.GetResponse();
    StreamReader r = new StreamReader(response.GetResponseStream());
    for (string line = r.ReadLine(); line != null; line = r.ReadLine())
      Console.WriteLine(line);
  }
}