Man, this class is pretty!

Lecture Notes Nine: Basic Java Networking


Networking and utilities.

We start with the minimal server.

tucotuco.cs.indiana.edu% ls -l
total 4
-rw-r--r--   1 dgerman  students    1026 Jul 22 17:20 ServerOne.java
tucotuco.cs.indiana.edu% cat ServerOne.java
import java.net.*;                                              // for networking  
import java.io.*;                                               // for I/O  
 
class ServerOne {                                               // my class  
  public static void main(String[] args) {                      // my main method  
    try {                                                       // Exceptions will be thrown  
      ServerSocket serverSocket = new ServerSocket(49900, 10);  // create a ServerSocket on port 49900  
      process(serverSocket.accept());                           // process incoming call when it comes  
      serverSocket.close();                                     // close the ServerSocket  
    } catch (Exception e) { 
      System.out.println("Error in main: " + e);                // report the Exception  
    } 
  } 
  static void process(Socket incoming) {                        // process function receives an incoming  
    try {                                                       // Socket object that manages the call  
      BufferedReader in  = new BufferedReader(
                             new InputStreamReader(
                                   incoming.getInputStream())); // now I can read from it through in  

      PrintWriter    out =   new PrintWriter(
                                   incoming.getOutputStream()); // and I can write to it through out  
 
      out.println("Hello, this is Echo.\nEnter BYE to exit.");  // initial greeting and briefing  
      out.flush();                                              // make it appear immediately (flush the buffer)  
 
      boolean done = false;                                     // conversation is only starting  
      while (!done) {                                           // while we're not finished  
        String str = in.readLine();                             // get a line from the remote client  
        out.println("Echo: " + str);                            // send it back immediately preceded by Echo:  
        out.flush();                                            // make it appear immediately (flush the buffer)  
        if (str.trim().equals("BYE"))                           // then check the line from the user: if BYE then  
          done = true;                                          // we're done  
      }                                                         // and that's our dialoop  
      incoming.close();                                         // when done hang up  
    } catch (Exception e) {                                     // catch the Exception  
      System.out.println("Error in process: " + e);             // report the error  
    } 
  } 
} 
tucotuco.cs.indiana.edu% javac ServerOne.java
tucotuco.cs.indiana.edu% java ServerOne
Meanwhile, from oldschool.cs.indiana.edu:
oldschool.cs.indiana.edu%telnet tucotuco.cs.indiana.edu 49900
Trying 129.79.251.110...
Connected to tucotuco.cs.indiana.edu.
Escape character is '^]'.
Hello, this is Echo.
Enter BYE to exit.
Ha, ha, ha!
Echo: Ha, ha, ha!
Ha, ha!                 
Echo: Ha, ha!
Hmmm...
Echo: Hmmm...
Well...
Echo: Well...
Not a lot of creativity, don't you think? 
Echo: Not a lot of creativity, don't you think? 
Grrr...
Echo: Grrr...
At this point we attempt a connection from bobac.cs.indiana.edu:
bobac.cs.indiana.edu% telnet tucotuco.cs.indiana.edu 49900
Trying 129.79.251.110...
Connected to tucotuco.cs.indiana.edu.
Escape character is '^]'.
 
 
we only get a connection that's been queued, but can't be processed yet.

Let's finish our conversation from oldschool.cs.indiana.edu.

Grrr...
Echo: Grrr...
Well, OK, I need to hang up now, other people are waiting, too   
Echo: Well, OK, I need to hang up now, other people are waiting, too
See you
Echo: See you
BYE
Echo: BYE
Connection closed by foreign host.
oldschool.cs.indiana.edu%
Our bobac.cs.indiana.edu screen comes to life but only briefly:
bobac.cs.indiana.edu% telnet tucotuco.cs.indiana.edu 49900
Trying 129.79.251.110...
Connected to tucotuco.cs.indiana.edu.
Escape character is '^]'.
Connection closed by foreign host.
bobac.cs.indiana.edu%
Let's make a change that would keep the server up and running. Even if it cannot talk to more than one client at a time at least it can talk to the next client once it's finished with one client.

So the change we need to make is marked in #0066cc below:

tucotuco.cs.indiana.edu% ls
ServerOne.java  ServerTwo.java
tucotuco.cs.indiana.edu% cat ServerTwo.java
import java.net.*; 
import java.io.*; 
 
class ServerTwo {
  public static void main(String[] args) {
    try {
      ServerSocket serverSocket = new ServerSocket(49900, 10); 
      while (true) {
        process(serverSocket.accept()); 
      } 
      // serverSocket.close(); 
    } catch (Exception e) { 
      System.out.println("Error in main: " + e); 
    } 
  } 
  static void process(Socket incoming) {
    try { 
      BufferedReader in  = new BufferedReader(
                             new InputStreamReader(
                               incoming.getInputStream())); 
 
      PrintWriter    out =   new PrintWriter(
                                   incoming.getOutputStream()); 
 
      out.println("Hello, this is Echo.\nEnter BYE to exit."); 
      out.flush();  
 
      boolean done = false; 
      while (!done) {
        String str = in.readLine(); 
        out.println("Echo: " + str); 
        out.flush(); 
        if (str.trim().equals("BYE")) 
          done = true; 
      } 
      incoming.close(); 
    } catch (Exception e) { 
      System.out.println("Error in process: " + e); 
    } 
  } 
} 
tucotuco.cs.indiana.edu% javac ServerTwo.java
tucotuco.cs.indiana.edu% java ServerTwo
This new server has been started. We go to oldschool and try to connect.

oldschool.cs.indiana.edu%
oldschool.cs.indiana.edu%telnet tucotuco.cs.indiana.edu 49900
Trying 129.79.251.110...
Connected to tucotuco.cs.indiana.edu.
Escape character is '^]'.
Hello, this is Echo.
Enter BYE to exit.
Hello again, dear Echo, it is so nice to see you again.
Echo: Hello again, dear Echo, it is so nice to see you again.
It is indeed.                               
Echo: It is indeed.
We try to connect from bobac at this point:

bobac.cs.indiana.edu% 
bobac.cs.indiana.edu% 
bobac.cs.indiana.edu% telnet tucotuco.cs.indiana.edu 49900
Trying 129.79.251.110...
Connected to tucotuco.cs.indiana.edu.
Escape character is '^]'.
 
So far, it's the same as before. But let's hang up on oldschool:

It is indeed.                               
Echo: It is indeed. 
OK, I need to go now again, we're doing an experiment...
Echo: OK, I need to go now again, we're doing an experiment...
See you, bobac is on the other line
Echo: See you, bobac is on the other line
BYE
Echo: BYE
Connection closed by foreign host.
oldschool.cs.indiana.edu%

and let's watch what happens on bobac:
Trying 129.79.251.110...
Connected to tucotuco.cs.indiana.edu.
Escape character is '^]'.
Hello, this is Echo.
Enter BYE to exit.
We see that we've been queued and when time comes we get to talk to the Echo.
Hello, this is Echo.
Enter BYE to exit.
Nifty, isn't it?... 
Echo: Nifty, isn't it?... 
OK, I'll let you go...  
Echo: OK, I'll let you go...
BYE                                      
Echo: BYE
Connection closed by foreign host.
bobac.cs.indiana.edu% 
And of course, on tucotuco the server keeps going:
tucotuco.cs.indiana.edu% javac ServerTwo.java
tucotuco.cs.indiana.edu% java ServerTwo 

for as long as we let it run.
tucotuco.cs.indiana.edu% java ServerTwo
^Ctucotuco.cs.indiana.edu% 
Now let's make Echo able to speak to more than one client at a time.

The part that you haven't seen before is in #0066cc.

tucotuco.cs.indiana.edu% ls 
ServerOne.java    ServerThree.java  ServerTwo.java
tucotuco.cs.indiana.edu% cat ServerThree.java
import java.net.*; 
import java.io.*; 
 
class ServerThree {
  public static void main(String[] args) {
    try {
      ServerSocket serverSocket = new ServerSocket(49900, 10); 
      while (true) {
        process(serverSocket.accept()); 
      } 
      // serverSocket.close(); 
    } catch (Exception e) { 
      System.out.println("Error in main: " + e); 
    } 
  } 
  static void process(Socket incoming) { 
    Operator operator = new Operator(incoming); 
    operator.start(); 
  } 
} 
 
class Operator extends Thread { 
  Socket incoming; 
  Operator(Socket call) { 
    incoming = call; 
  } 
  public void run() { 
    try { 
      BufferedReader in  = new BufferedReader(
                             new InputStreamReader(
                               incoming.getInputStream())); 
 
      PrintWriter    out =   new PrintWriter(
                                   incoming.getOutputStream()); 
 
      out.println("Hello, this is Echo.\nEnter BYE to exit."); 
      out.flush();  
 
      boolean done = false; 
      while (!done) {
        String str = in.readLine(); 
        out.println("Echo: " + str); 
        out.flush(); 
        if (str.trim().equals("BYE")) 
          done = true; 
      } 
      incoming.close(); 
    } catch (Exception e) { 
      System.out.println("Error in process: " + e); 
    } 
  }
}
 
tucotuco.cs.indiana.edu% javac ServerThree.java
tucotuco.cs.indiana.edu% java ServerThree

We've used Threads, so we will explain them as well, on Monday.

For now let's see how ServerThree operates.

We start it

tucotuco.cs.indiana.edu% ls
ServerOne.java    ServerThree.java  ServerTwo.java
tucotuco.cs.indiana.edu% javac ServerThree.java 
tucotuco.cs.indiana.edu% java ServerThree
 
and access it from oldschool
oldschool.cs.indiana.edu%telnet tucotuco 49900
Trying 129.79.251.110...
Connected to tucotuco.cs.indiana.edu.
Escape character is '^]'.
Hello, this is Echo.
Enter BYE to exit.
Are you really multi-threaded? 
Echo: Are you really multi-threaded? 
Let me check that             
Echo: Let me check that
 
and before we close that connection we also call from bobac
bobac.cs.indiana.edu% telnet tucotuco 49900
Trying 129.79.251.110...
Connected to tucotuco.cs.indiana.edu.
Escape character is '^]'.
Hello, this is Echo.
Enter BYE to exit.
I am amazed...
Echo: I am amazed...
Me too!
Echo: Me too!
 
and verify that both connections are live.

We then look at a network client, as simple as this one below.

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

public class Client {
  public static void main(String[] args) {
    try {
      Socket con = new Socket("tucotuco.cs.indiana.edu", 49900);
      BufferedReader in = new BufferedReader(
                            new InputStreamReader(
                              con.getInputStream()));
      PrintWriter out = new PrintWriter(con.getOutputStream(), true);
      for (int i = 0; i < 10; i++) {
        System.out.println(in.readLine());
        out.println("I am " + args[0] + " " + i);
        out.flush();
        Thread.sleep(1000);
      }
     out.println("BYE"); out.flush();
    } catch (Exception e) {
      System.out.println("E: " + e);
    }
  }                                
}
That's as far as it goes, for basic networking.


Last updated: Apr 17, 2002 by Adrian German for NC009