Distributed Program Construction

Fall 2002

Lecture 3:  Network Programming: TCP/IP, Streams and Sockets

Peter Druschel



COMP 413

COMP 413




COMP 413
  Connectionless, packet delivery protocol, over virtual (software) network. Best-effort, but unreliable: packets may be lost, duplicated, delayed, out-of-order, with no indication to service user

Roles: 1. defines packet format and processing; 2. addressing hosts; 3. routing packets

IP global addressing scheme:



COMP 413
 




COMP 413
 
  Properties: Stream-oriented (ordered); Virtual circuit connection (reliable); buffered transfer (efficient); full-duplex

positive acknowledgement with retransmission:



COMP 413
 
  Congestion control: severe delays due to overload at routers (packet loss)
problem: endpoints see delay - might retransmit
solution: window = min(advertisement, congestion) Connection Establishment

Connection identified by a pair of endpoints (host,port)

Three-way handshake: After connection, bi-directional stream, e.g.: Closing connection (3-way)

COMP 413

DNS




COMP 413
 

Introduction to Streams

The model: Properties of streams:

COMP 413

Client-Side Networking with TCP











The model:
 




COMP 413
 
 

A TCP Client Example








import java.io.*;
import java.net.*;

// Get an html page and print it on the console.
public class GetPage {
  public static void main(String[] args) throws IOException {
    // Get the URL.
    URL url = new URL(args[0]);
    String host = url.getHost();
    int port = url.getPort();
    String file = url.getFile();
    if (port == -1) port = 80;
    // Open a TCP socket.
    Socket socket = new Socket(host, port);
    // Prepare to read/write data.
    OutputStream rawOut = socket.getOutputStream();
    InputStream rawIn = socket.getInputStream();
    BufferedOutputStream bufOut = new BufferedOutputStream(rawOut);
    DataOutputStream out = new DataOutputStream(bufOut);
    DataInputStream in = new DataInputStream(rawIn);
    // Send the http request.
    out.writeBytes("GET "+file+" HTTP/1.0\r\n\r\n");
    out.flush();
    // Receive the page and echo to the console.
    String input;
    while((input = in.readLine()) != null)
      System.out.println(input);
  }
}
 



COMP 413

Server-Side Networking with TCP

The model:



COMP 413

A TCP Server Example







import java.io.*;
import java.net.*;
 

// An echo server.
public class EchoServer {
  public static void main(String[] args) throws IOException {
    int port = Integer.parseInt(args[0]);
    // Wait for client?s connection
    ServerSocket server = new ServerSocket(port);
    Socket client = server.accept();
    server.close();
    // Handle a connection and exit.
    try {
      InputStream in = client.getInputStream();
      OutputStream out = client.getOutputStream();
      new PrintStream(out).println("Welcome!");
      int x;
      while((x = in.read()) > -1)
        out.write(x);
    } finally {
      client.close();
    }
  }
}



COMP 413
 
 

Final Notes on TCP Servers

Non-blocking servers:

// Handle two connections simultaneously.
while(true) {
  if (in1.available()) {
    read from InputStream 1
    process the data
  }
  if (in2.available()) {
    read from InputStream 2
    process the data
  }
}

Multithreaded servers:

// The ?main? thread.
ServerSocket server = new ServerSocket(port);
while(true) {
  Socket client = server.accept();
  // Creating and starting a separate new thread
  // to handle the connection.
  Thread thread = new ConnectionThread(client);
  thread.start();
}



COMP 413

Datagram Networking

The model: Notice:

COMP 413

Datagram Networking Example

import java.io.*;
import java.net.*;

// An echo server, this time with UDP.
public class EchoServer {
  public static void main(String[] args) throws IOException {
    // Listen for incoming messages.
    int port = Integer.parseInt(args[0]);
    DatagramSocket socket = new DatagramSocket(port);
    Byte[] buffer = new byte[65535];
    DatagramPacket packet =
      new DatagramPacket(buffer, buffer.length);
    socket.receive(packet);
    // Handle a message.
    InetAddress addr = packet.getAddress();
    port = packet.getPort();
    byte[] data = packet.getData();
    int len = packet.getLength();
    packet = new DatagramPacket(data,len,addr,port);
    socket.send(packet);
  }
}



COMP 413

Datagram Networking Example (Cont'd.)







import java.io.*;
import java.net.*;

// A client for the echo server.
public class EchoClient {
  public static void main(String[] args) throws IOException {
    InetAddress host = InetAddress.getByName(args[0]);
    int port = Integer.parseInt(args[1]);
    String message = args[2];
    // Send the message.
    ByteArrayOutputStream byteOut =
      new ByteArrayOutputStream();
    DataOutputStream dataOut =
      new DataOutputStream(byteOut);
    dataOut.writeUTF(message);
    byte[] data = byteOut.toByteArray();
    DatagramPacket packet =
      new DatagramPacket(data,data.length,host,port);
    DatagramSocket socket =
      new DatagramSocket();
    socket.send(packet);
    // Receive and print the message.
    byte[] buffer = new byte[65535];
    packet = new DatagramPacket(buffer,buffer.length);
    socket.receive(packet);
    data = packet.getData();
    int length = packet.getLength();
    ByteArrayInputStream byteIn =
      new ByteArrayInputStream(data, 0, length);
    DataInputStream dataIn =
      new DataInputStream(byteIn);
    String result = dataIn.readUTF();
    System.out.println("Received: "+result);
  }
}



COMP 413