Man, this class is pretty!

Lecture Notes Two: Network Fundamentals


A simple threaded server with a simple (applet) client.

We start from a few notes already existing:

There's a little more also, that we can find in the A201 notes on event handling (e.g., here).

So what do we do today?

We might also need these docs: (Socket, ServerSocket)

Let's get started now.

First, create a directory echo under your htdocs.

Then place this file inside it.

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

class ServerThree {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(39999, 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); 
        } 
    }
}
Notice that you should use a different port.

You can start it from the command line with java ServerThree.

It can support up to 10 simultaneous connections.

What can you do with this?

  1. you can access it with telnet from bobac
  2. you could even access it from a browser (not very glitzy though)
In any event both approaches work.

So what do we do now?

Let's build our own client:

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

public class Client {
    public static void main(String[] args) {
        try {
            Socket con = new Socket(args[0], 
                                    Integer.parseInt(args[1])); 
            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);
        }
    }                                
} 
Do you see what it's doing?

How can we use it?

Well, place it in a folder and then run it from two or three machines.

(Be sure to do it simultaneously, to check it thoroughly).

You'd get something like this (in 10 seconds/client).

blesmol.cs.indiana.edu% pwd         
/nfs/paca/home/user1/dgerman/javaNetwork
blesmol.cs.indiana.edu% ls -l
total 1
-rw-r--r--   1 dgerman  faculty       717 Jan 17 14:49 Client.java
blesmol.cs.indiana.edu% javac Client.java
blesmol.cs.indiana.edu% ls -l
total 3
-rw-r--r--   1 dgerman  faculty      1463 Jan 17 14:49 Client.class
-rw-r--r--   1 dgerman  faculty       717 Jan 17 14:49 Client.java
blesmol.cs.indiana.edu% java Client burrowww.cs.indiana.edu 39999
Hello, this is Echo.
Enter BYE to exit.
Echo: I am burrowww.cs.indiana.edu 0
Echo: I am burrowww.cs.indiana.edu 1
Echo: I am burrowww.cs.indiana.edu 2
Echo: I am burrowww.cs.indiana.edu 3
Echo: I am burrowww.cs.indiana.edu 4
Echo: I am burrowww.cs.indiana.edu 5
Echo: I am burrowww.cs.indiana.edu 6
Echo: I am burrowww.cs.indiana.edu 7
blesmol.cs.indiana.edu% 
Note I was calling from blesmol and I could have called from any burrow machine at the same time.

Now let's build a better client, with a GUI.

burrowww.cs.indiana.edu% pwd
/nfs/paca/home/user1/dgerman/apache/apache_1.3.22/htdocs/echo
burrowww.cs.indiana.edu% ls -l
total 10
-rw-r--r--   1 dgerman  faculty      1975 Jan 17 14:54 ChatApplet.class
-rw-r--r--   1 dgerman  faculty      1045 Jan 17 14:54 ChatApplet.java
-rw-r--r--   1 dgerman  faculty      1490 Jan 17 14:10 Operator.class
-rw-r--r--   1 dgerman  faculty       927 Jan 17 14:10 ServerThree.class
-rw-r--r--   1 dgerman  faculty      1223 Jan 17 14:10 ServerThree.java
-rw-r--r--   1 dgerman  faculty       123 Jan 17 14:54 chat.html
burrowww.cs.indiana.edu% cat ChatApplet.java
import java.applet.*;
import java.awt.*;
import java.net.*; 

public class ChatApplet extends Applet {
    TextArea text; 
    Label label;
    TextField input;
    String user; 
    public void init() {
        URL codebase = getCodeBase(); 
        user = getParameter("user"); 
        if (user == null) user = "anonymous";
        text = new TextArea(); 
        text.setEditable(false); 
        label = new Label("Type here: "); 
        input = new TextField(); 
        input.setEditable(true); 
        setLayout(new BorderLayout());
        add("Center", text); 
        Panel panel = new Panel();
        panel.setLayout(new BorderLayout());
        panel.add("West", label); 
        panel.add("Center", input); 
        add("South",  panel); 
        text.appendText("URL: " + codebase + "\n"); 
    }
    public void start() {
        text.appendText("Your name is: " + user + "\n");
    }
    public boolean handleEvent(Event event) {
        switch (event.id) {
        case Event.ACTION_EVENT:
            if (event.target == input) {
                text.appendText(user + ": " + input.getText() + "\n"); 
                input.setText(""); 
                return true; 
            }
        }
        return false; 
    } 
} 

burrowww.cs.indiana.edu% cat chat.html
<html>
  <applet code=ChatApplet
          width=400 height=400>
    <param name=user value="Michael"> 
  </applet>
</html>burrowww.cs.indiana.edu%
Now let''s make a change for this to contact our server.

(I use some of the things shown here, but only a first few).

import java.applet.*;
import java.awt.*;
import java.net.*; 
import java.io.*; 

public class ChatClient extends Applet {
    TextArea text; 
    Label label;
    TextField input;
    int port; 
    String host; 
    public void init() {

	URL codebase = getCodeBase(); 

	String prt = getParameter("port"); 
	if (prt == null) prt = "39999";

	try {
	    port = Integer.parseInt(prt); 
	} catch (Exception e) {
	    port = 39999; 
	}

	host = getParameter("host"); 
	if (host == null) host = "burrowww.cs.indiana.edu";        

	text = new TextArea(); 
	text.setEditable(false); 

	label = new Label("Type here: "); 

	input = new TextField(); 
	input.setEditable(true); 

	setLayout(new BorderLayout());
	add("Center", text); 
	Panel panel = new Panel();
	panel.setLayout(new BorderLayout());
	panel.add("West", label); 
	panel.add("Center", input); 
	add("South",  panel); 
	text.appendText("I'm coming from: " + codebase + "\n"); 
    }

    public void start() {
	text.appendText("Welcome to Java networking.\n");
    }

    public boolean handleEvent(Event event) {
	switch (event.id) {
	case Event.ACTION_EVENT:
	    if (event.target == input) {
		text.appendText("You: " + input.getText() + "\n"); 
		input.setText(""); 
		text.appendText("Server: (" + contactServer(
					       input.getText()
                                              ) + ")" ); 
		return true; 
	    }
	}
	return false; 
    } 

    String contactServer(String msg) {
	
        try {
            Socket con = new Socket(
                                    host, 
				    port
				    );

            BufferedReader in = new BufferedReader(
			          new InputStreamReader(
				    con.getInputStream()));

            PrintWriter out = new PrintWriter(con.getOutputStream(), true);

	    out.println(msg);
	    out.flush();

	    return in.readLine(); 


        } catch (Exception e) {
            return "E: " + e;
        }
	
    }
}
The HTML is now:
burrowww.cs.indiana.edu% pwd
/nfs/paca/home/user1/dgerman/apache/apache_1.3.22/htdocs/echo
burrowww.cs.indiana.edu% cat chatClient.html
<html>
  <applet code=ChatClient
          width=400 height=400>
    <param name=port value="39999"> 
    <param name=host value="burrowww.cs.indiana.edu"> 
  </applet>
</html>burrowww.cs.indiana.edu%
And this should be a bit less than what we expected.

Why?

(It should be obvious).

So let's reorganize the applet a little bit.

Here are the two big projects for today:

  1. Chat

  2. NetOthello

You can't use them without me starting the server(s).

I will provide all the source code so we all can install them and look at them.

The HTML file:

<hr>

<applet code="Othello.class" width=350 height=400>

  <param name=host value=localhost>
  <param name=port value=39999>

</applet>

<hr>


Last updated: Jan 17, 2002 by Adrian German for A348/A548