The Artima Developer Community
Sponsored Link

Objects and Java Seminar by Bill Venners
Network Programming
Lecture Handout

Agenda


Network Programming


IP and Sockets


IP Addresses


Client/Server Computing


Port Number


Localhost


The Summer Server Application

  1 // In file network/ex1/SummerServer.java
  2 import java.net.*;
  3 import java.io.*;
  4 import java.util.StringTokenizer;
  5
  6 public class SummerServer {
  7
  8     public static final int PORT = 2000;
  9
 10     private static class InvalidLongException
 11         extends Exception {
 12
 13         private String message;
 14
 15         InvalidLongException(String s) {
 16             message = s;
 17         }
 18
 19         public String getMessage() {
 20             return message;
 21         }
 22     }
 23
 24     public static void main(String[] args)
 25         throws IOException {
 26
 27         ServerSocket listener =
 28             new ServerSocket(PORT);
 29
 30         try {
 31
 32             for (;;) {
 33
 34                 Socket sock = listener.accept();
 35
 36                 try {
 37
 38                     serveClient(sock);
 39                 }
 40                 finally {
 41                     sock.close();
 42                 }
 43             }
 44         }
 45         finally {
 46             listener.close();
 47         }
 48     }
 49
 50     private static void serveClient(Socket sock)
 51         throws IOException {
 52
 53         BufferedReader reader = new BufferedReader(
 54             new InputStreamReader(
 55                 sock.getInputStream()));
 56
 57         BufferedWriter writer = new BufferedWriter(
 58             new OutputStreamWriter(
 59                 sock.getOutputStream()));
 60
 61         for (;;) {
 62
 63             String s = reader.readLine();
 64
 65             if (s == null) {
 66                 break;
 67             }
 68
 69             String outString;
 70             try {
 71                 outString =
 72                     Long.toString(sumString(s));
 73             }
 74             catch(InvalidLongException e) {
 75                 outString = e.getMessage();
 76             }
 77             writer.write(outString);
 78             writer.newLine();
 79             writer.flush();
 80         }
 81     }
 82
 83     private static long sumString(String s)
 84         throws InvalidLongException {
 85
 86         long sum = 0;
 87
 88         StringTokenizer st = new StringTokenizer(s);
 89         String token;
 90         while (st.hasMoreTokens()) {
 91             token = st.nextToken();
 92             try {
 93                 sum += Long.parseLong(token);
 94             }
 95             catch (NumberFormatException e) {
 96                 throw new InvalidLongException(
 97                     "Invalid number: " + token);
 98             }
 99         }
100
101         return sum;
102     }
103 }
104

 1 // In file network/ex1/SummerClient.java
 2 import java.net.*;
 3 import java.io.*;
 4
 5 public class SummerClient {
 6
 7     public static void main(String[] args)
 8         throws IOException {
 9
10         InetAddress ia = InetAddress.getByName(null);
11
12         Socket sock = new Socket(ia, SummerServer.PORT);
13
14         try {
15
16             BufferedReader serverReader =
17                 new BufferedReader(
18                     new InputStreamReader(
19                         sock.getInputStream()));
20
21             BufferedWriter serverWriter =
22                 new BufferedWriter(
23                     new OutputStreamWriter(
24                         sock.getOutputStream()));
25
26             LineNumberReader stdinReader =
27                 new LineNumberReader(
28                     new BufferedReader(
29                         new InputStreamReader(
30                             System.in)));
31
32             for (;;) {
33
34                 String userLine = stdinReader.readLine();
35
36                 if (userLine == null ||
37                     userLine.length() == 0) {
38
39                     break;
40                 }
41
42                 serverWriter.write(userLine);
43                 serverWriter.newLine();
44                 serverWriter.flush();
45
46                 String serverLine = serverReader.readLine();
47                 System.out.println(serverLine);
48             }
49         }
50         finally {
51             sock.close();
52         }
53     }
54 }
55

Handling Multiple Clients Concurrently

  1 // In file network/ex2/SummerServer.java
  2 import java.net.*;
  3 import java.io.*;
  4 import java.util.StringTokenizer;
  5
  6 public class SummerServer {
  7
  8     public static final int PORT = 2000;
  9
 10     private static class InvalidLongException
 11         extends Exception {
 12
 13         private String message;
 14
 15         InvalidLongException(String s) {
 16             message = s;
 17         }
 18
 19         public String getMessage() {
 20             return message;
 21         }
 22     }
 23
 24     private static class SummerService
 25         extends Thread {
 26
 27         private Socket sock;
 28
 29         public SummerService(Socket sock) {
 30             this.sock = sock;
 31         }
 32
 33         public void run() {
 34
 35             try {
 36
 37                 BufferedReader reader =
 38                     new BufferedReader(
 39                         new InputStreamReader(
 40                             sock.getInputStream()));
 41
 42                 BufferedWriter writer =
 43                     new BufferedWriter(
 44                         new OutputStreamWriter(
 45                             sock.getOutputStream()));
 46
 47                 for (;;) {
 48
 49                     String s = reader.readLine();
 50
 51                     if (s == null) {
 52                         break;
 53                     }
 54
 55                     String outString;
 56                     try {
 57                         outString =
 58                             Long.toString(sumString(s));
 59                     }
 60                     catch(InvalidLongException e) {
 61                         outString = e.getMessage();
 62                     }
 63                     writer.write(outString);
 64                     writer.newLine();
 65                     writer.flush();
 66                 }
 67             }
 68             catch (IOException e) {
 69             }
 70             finally {
 71                 try {
 72                     sock.close();
 73                 }
 74                 catch (IOException e) {
 75                 }
 76             }
 77         }
 78     }
 79
 80     public static void main(String[] args)
 81         throws IOException {
 82
 83         ServerSocket listener = new ServerSocket(PORT);
 84
 85         try {
 86
 87             for (;;) {
 88
 89                 Socket sock = listener.accept();
 90
 91                 SummerService ss =
 92                     new SummerService(sock);
 93                 ss.start();
 94             }
 95         }
 96         finally {
 97             listener.close();
 98         }
 99     }
100
101     private static long sumString(String s)
102         throws InvalidLongException {
103
104         long sum = 0;
105
106         StringTokenizer st = new StringTokenizer(s);
107         String token;
108         while (st.hasMoreTokens()) {
109             token = st.nextToken();
110             try {
111                 sum += Long.parseLong(token);
112             }
113             catch (NumberFormatException e) {
114                 throw new InvalidLongException(
115                     "Invalid number: " + token);
116             }
117         }
118
119         return sum;
120     }
121 }
122

 1 // In file network/ex2/SummerClient.java
 2 import java.net.*;
 3 import java.io.*;
 4
 5 public class SummerClient {
 6
 7     public static void main(String[] args)
 8         throws IOException {
 9
10         InetAddress ia = InetAddress.getByName(null);
11
12         Socket sock = new Socket(ia,
13             SummerServer.PORT);
14
15         try {
16
17             BufferedReader serverReader =
18                 new BufferedReader(
19                     new InputStreamReader(
20                         sock.getInputStream()));
21
22             BufferedWriter serverWriter =
23                 new BufferedWriter(
24                     new OutputStreamWriter(
25                         sock.getOutputStream()));
26
27             LineNumberReader stdinReader =
28                 new LineNumberReader(
29                     new BufferedReader(
30                         new InputStreamReader(
31                             System.in)));
32
33             for (;;) {
34
35                 String userLine =
36                     stdinReader.readLine();
37
38                 if (userLine == null ||
39                     userLine.length() == 0) {
40
41                     break;
42                 }
43
44                 serverWriter.write(userLine);
45                 serverWriter.newLine();
46                 serverWriter.flush();
47
48                 String serverLine =
49                     serverReader.readLine();
50                 System.out.println(serverLine);
51             }
52         }
53         finally {
54             sock.close();
55         }
56     }
57 }
58

TCP versus UDP


Datagrams


Using Datagrams


The Clock Server

  1 // In file network/ex3/ClockServer.java
  2 import java.net.*;
  3 import java.io.*;
  4 import java.util.StringTokenizer;
  5 import java.util.Vector;
  6 import java.util.Date;
  7
  8 public class ClockServer {
  9
 10     public static final int REGISTRATION_PORT = 2001;
 11     private final static int ADDR_BYTE_SIZE = 4;
 12
 13     private Vector mailingList = new Vector();
 14
 15     public static class AddressAndPort
 16         implements Serializable {
 17
 18         private InetAddress addr;
 19         private int port;
 20
 21         public AddressAndPort(InetAddress addr, int port) {
 22
 23             this.addr = addr;
 24             this.port = port;
 25         }
 26
 27         public InetAddress getAddress() {
 28             return addr;
 29         }
 30
 31         public int getPort() {
 32             return port;
 33         }
 34
 35         public boolean equals(Object o) {
 36
 37             if (o == null) {
 38                 return false;
 39             }
 40
 41             AddressAndPort anp;
 42
 43             try {
 44                 anp = (AddressAndPort) o;
 45             }
 46             catch (ClassCastException e) {
 47                 return false;
 48             }
 49
 50             if (addr.equals(anp.addr) && port == anp.port) {
 51                 return true;
 52             }
 53             else {
 54                 return false;
 55             }
 56         }
 57     }
 58
 59     private class RegistrationService extends Thread {
 60
 61         private Socket sock;
 62
 63         public void run() {
 64
 65             ServerSocket listener;
 66             try {
 67                 listener =
 68                     new ServerSocket(REGISTRATION_PORT);
 69             }
 70             catch (IOException e) {
 71                 // Need to signal main thread that
 72                 // no one is getting registered.
 73                 return;
 74             }
 75             try {
 76
 77                 for (;;) {
 78
 79                     Socket sock;
 80                     try {
 81                         sock = listener.accept();
 82                     }
 83                     catch (IOException e) {
 84                         System.out.println(e.toString());
 85                         e.printStackTrace();
 86                         continue;
 87                     }
 88
 89                     System.out.println("Got a connection.");
 90                     registerClient(sock);
 91                 }
 92             }
 93             finally {
 94                 try {
 95                     listener.close();
 96                 }
 97                 catch (IOException e) {
 98                 }
 99             }
100         }
101
102         private void registerClient(Socket sock) {
103
104             AddressAndPort anp;
105
106             // Grab the data from the client.
107             try {
108
109                 ObjectInputStream ois =
110                     new ObjectInputStream(
111                         new BufferedInputStream(
112                             sock.getInputStream()));
113
114                 anp = (AddressAndPort) ois.readObject();
115             }
116             catch (ClassNotFoundException e) {
117                 // Just abort registering this client
118                 System.out.println(e.toString());
119                 e.printStackTrace();
120                 return;
121             }
122             catch (InvalidClassException e) {
123                 // Just abort registering this client
124                 System.out.println(e.toString());
125                 e.printStackTrace();
126                 return;
127             }
128             catch (StreamCorruptedException e) {
129                 // Just abort registering this client
130                 System.out.println(e.toString());
131                 e.printStackTrace();
132                 return;
133             }
134             catch (OptionalDataException e) {
135                 // Just abort registering this client
136                 System.out.println(e.toString());
137                 e.printStackTrace();
138                 return;
139             }
140             catch (IOException e) {
141                 // Just abort registering this client
142                 System.out.println(e.toString());
143                 e.printStackTrace();
144                 return;
145             }
146             finally {
147                 try {
148                     sock.close();
149                 }
150                 catch (IOException e) {
151                 }
152             }
153
154             synchronized (ClockServer.this) {
155
156                 int len = mailingList.size();
157
158                 boolean found = false;
159                 for (int i = 0; i < len; ++i) {
160
161                     Object o = mailingList.elementAt(i);
162
163                     if (anp.equals(o)) {
164                         found = true;
165                         System.out.println(
166                             "Already registered: (" +
167                                 anp.getAddress().getHostAddress() +
168                                     ", " + anp.getPort() + ")");
169                         break;
170                     }
171                 }
172
173                 if (!found) {
174                     mailingList.addElement(anp);
175                     System.out.println("Registering: (" +
176                         anp.getAddress().getHostAddress() + ", "
177                         + anp.getPort() + ")");
178                 }
179             }
180         }
181     }
182
183     private class TickerService extends Thread {
184
185         public void run() {
186
187             DatagramSocket sock;
188
189             try {
190                 sock = new DatagramSocket();
191             }
192             catch (SocketException e) {
193                 System.out.println(e.toString());
194                 e.printStackTrace();
195                 return;
196             }
197
198             for (;;) {
199
200                 // Create the Datagram
201                 Date date = new Date();
202
203                 ByteArrayOutputStream baos =
204                     new ByteArrayOutputStream();
205                 ObjectOutputStream oos;
206                 try {
207                     oos = new ObjectOutputStream(baos);
208                     oos.writeObject(date);
209                     oos.close();
210                 }
211                 catch (IOException e) {
212                     return;
213                 }
214
215                 byte[] data = baos.toByteArray();
216
217                 Vector ml;
218                 synchronized (this) {
219                     ml = (Vector) mailingList.clone();
220                 }
221
222                 int len = ml.size();
223
224                 for (int i = 0; i < len; ++i) {
225
226                     AddressAndPort anp =
227                         (AddressAndPort) ml.elementAt(i);
228
229                     InetAddress ia = anp.getAddress();
230                     int port = anp.getPort();
231
232                     DatagramPacket dp =
233                         new DatagramPacket(data,
234                             data.length, ia, port);
235
236                     try {
237                         sock.send(dp);
238                     }
239                     catch (IOException e) {
240                     }
241                     System.out.println("Sending to port: " +
242                         port);
243                 }
244
245                 try {
246                     Thread.sleep(1000);
247                 }
248                 catch (InterruptedException e) {
249                 }
250             }
251         }
252     }
253
254     private void start() {
255         RegistrationService rs = new RegistrationService();
256         rs.start();
257         TickerService ts = new TickerService();
258         ts.start();
259     }
260
261     public static void main(String[] args)
262         throws IOException {
263
264         ClockServer cs = new ClockServer();
265         cs.start();
266     }
267 }
268

The Clock Applet

  1 // In file network/ex3/ClockApplet.java
  2 import java.applet.*;
  3 import java.net.*;
  4 import java.io.*;
  5 import java.awt.*;
  6 import java.util.Date;
  7
  8 public class ClockApplet extends Applet {
  9
 10     private int myPort = 4000;
 11     private Runner runner;
 12     private CoolClockCanvas clock =
 13         new CoolClockCanvas();
 14
 15     private class Runner extends Thread {
 16
 17         private boolean stopRequested;
 18
 19         void requestStop() {
 20             stopRequested = true;
 21         }
 22
 23         public void run() {
 24
 25             for (;;) {
 26
 27                 if (stopRequested) {
 28                     return;
 29                 }
 30
 31                 try {
 32                     InetAddress ia =
 33                         InetAddress.getByName(null);
 34
 35                     ClockServer.AddressAndPort myANP =
 36                         new ClockServer.AddressAndPort(
 37                             ia, myPort);
 38
 39                     Socket sock = new Socket(ia,
 40                         ClockServer.REGISTRATION_PORT);
 41
 42                     try {
 43
 44                         ObjectOutputStream oos =
 45                             new ObjectOutputStream(
 46                                 new BufferedOutputStream(
 47                                     sock.getOutputStream()));
 48
 49                         try {
 50                             oos.writeObject(myANP);
 51                         }
 52                         finally {
 53                             oos.close();
 54                         }
 55                     }
 56                     finally {
 57                         sock.close();
 58                     }
 59
 60                     DatagramSocket dgsock;
 61
 62                     try {
 63                         dgsock = new DatagramSocket(myPort);
 64                     }
 65                     catch (SocketException e) {
 66                         System.out.println(e.toString());
 67                         e.printStackTrace();
 68                         return;
 69                     }
 70
 71                     for (;;) {
 72
 73                         int packetSize = 1000;
 74                         byte[] buf = new byte[packetSize];
 75
 76                         DatagramPacket dp =
 77                             new DatagramPacket(
 78                                 buf, packetSize);
 79
 80                         dgsock.receive(dp);
 81                         System.out.println("Datagram received");
 82
 83                         byte[] data = dp.getData();
 84
 85                         ByteArrayInputStream bais =
 86                             new ByteArrayInputStream(data);
 87
 88                         ObjectInputStream ois;
 89                         Date date;
 90                         try {
 91                             ois = new ObjectInputStream(bais);
 92                             date = (Date) ois.readObject();
 93                             ois.close();
 94                         }
 95                         catch (IOException e) {
 96                             System.out.println(e.toString());
 97                             e.printStackTrace();
 98                             continue;
 99                         }
100                         catch (ClassNotFoundException e) {
101                             System.out.println(e.toString());
102                             e.printStackTrace();
103                             continue;
104                         }
105
106                         clock.setTime(date);
107                     }
108                 }
109                 catch (IOException e) {
110                     System.out.println(e.toString());
111                     e.printStackTrace();
112                     return;
113                 }
114             }
115         }
116     }
117
118     public void init() {
119
120         String portStr = getParameter("port");
121         if (portStr != null) {
122             try {
123                 myPort = Integer.parseInt(portStr);
124             }
125             catch (NumberFormatException e) {
126                 // Use default port number
127             }
128         }
129
130         setLayout(new BorderLayout());
131         add("Center", clock);
132     }
133
134     public synchronized void start() {
135
136         if (runner == null) {
137
138             runner = new Runner();
139             runner.start();
140         }
141     }
142
143     public synchronized void stop() {
144
145         if (runner != null) {
146
147             runner.requestStop();
148             runner = null;
149         }
150     }
151 }
152

  1 // In file network/ex3/CoolClockCanvas.java
  2 import java.awt.*;
  3 import java.awt.event.*;
  4 import java.util.*;
  5
  6 class CoolClockCanvas extends Canvas {
  7
  8     private Color backgroundColor = Color.lightGray;
  9     private Color shadowColor = Color.gray;
 10     private Color tickShadowColor = Color.darkGray;
 11     private int xCircleCenter;
 12     private int yCircleCenter;
 13     private int xSecondHandTip;
 14     private int ySecondHandTip;
 15     private int secondHandRadius;
 16     private Date latestDate = new Date();
 17
 18     Thread runner;
 19
 20     CoolClockCanvas() {
 21
 22         setBackground(backgroundColor);
 23     }
 24
 25     public void setTime(Date date) {
 26
 27         latestDate = date;
 28         repaint();
 29     }
 30
 31     private Point getHandTip(int radius, int minutePos) {
 32
 33         double thetaInDegrees;
 34
 35         if (minutePos <= 15) {
 36
 37             thetaInDegrees = (15.0 - (double) minutePos) * 6.0;
 38         }
 39         else {
 40
 41             thetaInDegrees = 360.0 - (6.0 *
 42                 ((double) minutePos - 15.0));
 43         }
 44
 45         double thetaInRadians = (thetaInDegrees / 180.0) * Math.PI;
 46
 47         double radiusDouble = (double) radius;
 48
 49         int x = (int) Math.round(radiusDouble *
 50             Math.cos(thetaInRadians));
 51         int y = (int) Math.round(radiusDouble *
 52             Math.sin(thetaInRadians));
 53
 54         Point point = new Point(xCircleCenter + x,
 55             yCircleCenter - y);
 56
 57         return point;
 58     }
 59
 60     public void update(Graphics g) {
 61
 62         // Don't erase background because
 63         // double buffering in paint()
 64         // to reduce flicker.
 65         paint(g);
 66     }
 67
 68     synchronized public void paint(Graphics g) {
 69
 70         Dimension canvasSize = getSize();
 71
 72         // Double buffer to reduce flicker
 73         Image offscreenImage = createImage(
 74             canvasSize.width, canvasSize.height);
 75         Graphics og = offscreenImage.getGraphics();
 76
 77         // Take smaller of width and height of canvas, and subtract
 78         // ten from it. That will be the diameter of the clock's
 79         // face (the outer circle).
 80         int outerCircleDiameter = canvasSize.width;
 81         if (canvasSize.width > canvasSize.height) {
 82             outerCircleDiameter = canvasSize.height;
 83         }
 84         outerCircleDiameter -= 8;
 85
 86         int xOuterCircle = (canvasSize.width -
 87             outerCircleDiameter) / 2;
 88         int yOuterCircle = (canvasSize.height -
 89             outerCircleDiameter) / 2;
 90
 91         // Paint with background color first
 92         og.setColor(backgroundColor);
 93         og.fillRect(0, 0, canvasSize.width, canvasSize.height);
 94
 95         // Draw lines around the edge of the canvas, to give
 96         // it the appearance of a sunken panel.
 97         og.setColor(shadowColor);
 98         og.drawLine(0, 0, 0, canvasSize.height - 1);
 99         og.drawLine(0, 0, canvasSize.width - 1, 0);
100
101         og.setColor(Color.white);
102         og.drawLine(0, canvasSize.height - 1,
103             canvasSize.width - 1, canvasSize.height - 1);
104         og.drawLine(canvasSize.width - 1, 0,
105             canvasSize.width - 1, canvasSize.height - 1);
106
107
108         // Draw arcs around the face of the clock
109         // to give it a raised appearance.
110         og.setColor(Color.white);
111         og.drawArc(xOuterCircle, yOuterCircle,
112             outerCircleDiameter, outerCircleDiameter, 45, 180);
113         og.setColor(shadowColor);
114         og.drawArc(xOuterCircle, yOuterCircle,
115             outerCircleDiameter, outerCircleDiameter, 45, -180);
116
117         // Radius of tick marks is 4 pixels less than radius
118         // of outer circle
119         int fullRadius = (outerCircleDiameter / 2) - 4;
120
121         // Radius of tip of the second hand
122         secondHandRadius = fullRadius + 1;
123
124         int minuteHandRadius = secondHandRadius;
125         int hourHandRadius = (fullRadius * 2) / 3;
126
127         xCircleCenter = xOuterCircle + (outerCircleDiameter / 2);
128         yCircleCenter = yOuterCircle + (outerCircleDiameter / 2);
129
130         // Calculate the absolute x and y positions for the
131         // tick marks that aren't at 12, 3, 6, or 9:00.
132         double shortSideDouble = ((double) fullRadius) *
133             Math.cos(Math.PI / 6.0);
134         double longSideDouble = ((double) fullRadius) *
135             Math.sin(Math.PI / 6.0);
136         int shortSide = (int) (shortSideDouble + 0.5);
137         int longSide = (int) (longSideDouble + 0.5);
138
139         // Put up 12 tick marks
140         // 12:00
141         drawTickMark(og, xCircleCenter, yCircleCenter - fullRadius);
142
143         // 1:00
144         drawTickMark(og, xCircleCenter + shortSide,
145             yCircleCenter - longSide);
146
147         // 2:00
148         drawTickMark(og, xCircleCenter + longSide,
149             yCircleCenter - shortSide);
150
151         // 3:00
152         drawTickMark(og, xCircleCenter + fullRadius, yCircleCenter);
153
154         // 4:00
155         drawTickMark(og, xCircleCenter + longSide,
156             yCircleCenter + shortSide);
157
158         // 5:00
159         drawTickMark(og, xCircleCenter + shortSide,
160             yCircleCenter + longSide);
161
162         // 6:00
163         drawTickMark(og, xCircleCenter, yCircleCenter + fullRadius);
164
165         // 7:00
166         drawTickMark(og, xCircleCenter - shortSide,
167             yCircleCenter + longSide);
168
169         // 8:00
170         drawTickMark(og, xCircleCenter - longSide,
171             yCircleCenter + shortSide);
172
173         // 9:00
174         drawTickMark(og, xCircleCenter - fullRadius, yCircleCenter);
175
176         // 10:00
177         drawTickMark(og, xCircleCenter - longSide,
178             yCircleCenter - shortSide);
179
180         // 11:00
181         drawTickMark(og, xCircleCenter - shortSide,
182             yCircleCenter - longSide);
183
184         Calendar cal = new GregorianCalendar();
185         cal.setTime(latestDate);
186
187         // Calculate the hour hand tip position
188         int hours = cal.get(Calendar.HOUR);
189         int minutes = cal.get(Calendar.MINUTE);
190         if (hours == 12) {
191             hours = 0;
192         }
193         int minPosOfHourHand = (hours * 5) + (minutes / 12);
194         Point hourHandTip = getHandTip(hourHandRadius,
195             minPosOfHourHand);
196
197         // Calculate the minute hand tip position
198         Point minuteHandTip = getHandTip(minuteHandRadius, minutes);
199
200         // Calculate the second hand tip position
201         int secs = cal.get(Calendar.SECOND);
202         Point secondHandTip = getHandTip(secondHandRadius, secs);
203
204         // Draw shadow of the 3 by 3 square in the center.
205         og.setColor(Color.black);
206         og.fillRect(xCircleCenter - 1, yCircleCenter - 1, 3, 3);
207
208         // Draw the hour hand
209         og.setColor(Color.blue);
210         og.drawLine(xCircleCenter, yCircleCenter,
211             hourHandTip.x, hourHandTip.y);
212
213         // Draw the minute hand
214         og.drawLine(xCircleCenter, yCircleCenter,
215             minuteHandTip.x, minuteHandTip.y);
216
217         // Draw a 2 by 2 square in the center on top
218         // of the shadow and hour and minute hands.
219         og.setColor(Color.red);
220         og.fillRect(xCircleCenter - 1, yCircleCenter - 1, 2, 2);
221
222         // Draw the second hand
223         og.drawLine(xCircleCenter, yCircleCenter,
224             secondHandTip.x, secondHandTip.y);
225
226         xSecondHandTip = secondHandTip.x;
227         ySecondHandTip = secondHandTip.y;
228
229         g.drawImage(offscreenImage, 0, 0, this);
230     }
231
232     private void drawTickMark(Graphics g, int x, int y) {
233
234         g.setColor(tickShadowColor);
235         g.fillRect(x, y, 2, 2);
236         g.setColor(Color.white);
237         g.fillRect(x, y, 1, 1);
238     }
239 }

Multicast Protocol


URL and URLConnection


The Resource Grabber

 1 // In file network/ex5/ResourceGrabber.java
 2 import java.net.*;
 3 import java.io.*;
 4 import java.util.Date;
 5 import java.util.StringTokenizer;
 6
 7 public class ResourceGrabber {
 8
 9     public static void main(String[] args) {
10
11         if (args.length < 1) {
12             System.out.println(
13                 "Need URL and optional local filename.");
14             return;
15         }
16
17         try {
18
19             URL url  = new URL(args[0]);
20
21             System.out.println(
22                 "Connecting to resource...");
23             URLConnection conn = url.openConnection();
24             InputStream is = url.openStream();
25
26             try {
27
28                 // Get info about the resource
29                 String type = conn.getContentType();
30                 Date date = new Date(conn.getLastModified());
31                 String lastMod = date.toLocaleString();
32
33                 // Print the info
34                 System.out.println(
35                     "Grabbing resource\n    type: " + type
36                     + "\n    last modified: " + lastMod);
37
38                 FileOutputStream fos;
39                 if (args.length < 2) {
40
41                     String localFile = null;
42
43                     // Grab the simple file name from the
44                     // URL String
45                     String fullPath = url.getFile();
46                     StringTokenizer st =
47                         new StringTokenizer(fullPath, "/");
48                     while (st.hasMoreTokens()) {
49                        localFile = st.nextToken();
50                     }
51                     fos = new FileOutputStream(localFile);
52                 }
53                 else {
54                     fos = new FileOutputStream(args[1]);
55                 }
56
57                 try {
58
59                     BufferedOutputStream bos =
60                         new BufferedOutputStream(fos);
61                     BufferedInputStream bis =
62                         new BufferedInputStream(is);
63
64                     int c;
65                     int count = 0;
66
67                     while ((c = bis.read()) != -1) {
68                         bos.write(c);
69                         ++count;
70                     }
71
72                     if (count != 1) {
73                         System.out.println(count
74                             + " bytes downloaded.");
75                     }
76                     else {
77                         System.out.println(
78                             "1 byte downloaded.");
79                     }
80                }
81                finally {
82                    fos.close();
83                }
84             }
85             finally {
86                 is.close();
87             }
88         }
89         catch (MalformedURLException e) {
90             System.err.println(e.toString());
91             e.printStackTrace();
92         }
93         catch (IOException e) {
94             System.err.println(e.toString());
95             e.printStackTrace();
96         }
97     }
98 }

Exercises

Problem 1.

Write an application named GetServer.java that creates a ServerSocket on port 80. When a client request comes in, get an InputStream from the socket returned by read lines from the ServerSocket's accept() method, and wrap the InputStream in an InputStreamReader and a BufferedReader. Read one line at a time from the BufferedReader while the length of the line read does not equal 0 and the first character is not '\r' or '\n'. Each time you read a line from the BufferedReader, print the line out to the standard output. Once you are done reading lines, just close the socket by closing the BufferedReader.

What you'll end up printing out is HTTP requests sent by a web browser, which are always terminated by a blank line, as in:

GET /jvm/index.html HTTP/1.0
Referer: http://minovia/subscribe.html
Connection: Keep-Alive
User-Agent: Mozilla/4.7 [en] (Win98; I)
Host: minovia
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
<BLANK LINE>

Start your GetServer application and then open a web browser. Type in URLs into your browser's address bar such as:

http://127.0.0.1
or
http://127.0.0.1/this/is/a/longer/pathname/filename.html

Watch what output your GetServer prints and the web browser prints.

Problem 2.

Change your GetServer application from Problem 1 so that it also sends a response back to the client. First, get an OutputStream from the socket, and wrap that in a BufferedOutputStream and a DataOutputStream. Write the following line out to the client after reading in the HTTP request lines, and before closing the socket:
HTTP/1.0 404 Not found\r\n\r\n

Run your GetServer application again and look at what the web browser now prints when you hit 127.0.0.1 URLs.

Problem 3.

Change your GetServer application from Problem 2 so that each time a client request comes in, it fires off a new thread to handle the client. Name the thread class ServerThread. Test your application again with a web browser.

Problem 4.

Create a private instance method getFile() that returns a String and takes no arguments in your ServerThread class, and call the method from your run() method right after getting the DataOutputStream from the socket. Wrap the getFile() invocation in a try block that has a catch (Exception e) clause. In the catch clause, print the 404 Not Found response back to the client.

Move the code that gets a BufferedReader from the socket to the getFile() method. After getting the BufferedReader, make sure that the first three characters of the first line is "GET," as in:

GET /jvm/index.html HTTP/1.0

If the first three lines is not a GET, just throw an IOException back to the run() method.

Finally, parse out the second token of that line, which in the above case would be, "/jvm/index.html," and return that value from getFile().

Back in the main run() method of ServerThread, format an HTTP request that indicates an HTML document is being returned:

HTTP/1.1 200 OK\r\n
Content-Type: text/html\r\n\r\n

Finally, format the file name returned by getFile() into an HTML page like this:

<HTML>
<HEAD>
<TITLE>Requested File</TITLE>
</HEAD>
<BODY>
<H1>The requested file was: /jvm/index.html</H1>
</BODY>
</HTML>

Write this HTML page out to the client after the 200 OK response.

Start your GetServer once again and hit 127.0.0.1 URLs with your web browser.

Problem 5.

Please enhance your GetServer application yet again. Change the return value of getFile() to a java.io.File. Modify getFile() so that it returns an actual full path to the file requested in the GET, based on a hard-coded base directory. For your hard-coded base directory, select some directory that has web pages in it, such as the directory in which you installed your javadoc documentation. If the requested path turns out to be a directory, just append index.html to the path.

Back in the run() method, adjust the code so that the full path is printed out in the web page sent back to the client, such as:

<HTML>
<HEAD>
<TITLE>Requested File</TITLE>
</HEAD>
<BODY>
<H1>The requested file was: d:\hard\coded\dir\jvm\index.html</H1>
</BODY>
</HTML>

Problem 6.

Lastly, change the run() method such that it actually sends back an approprite MIME type and the actual file contents. First, create a new java.util.HashMap in the GetServer's main() method, and add to it the MIME types for several file extensions:
htm text/html
html text/html
txt text/plain
jpg image/jpeg
gif image/gif

Pass a reference to this HashMap to the constructor of every ServerThread.

In the ServerThread's run() method, figure out the appropriate MIME type by looking up the file's extension in the Map passed to the ServerThread's constructor. Send that MIME type back to the client in the Content-Type header rather than just text/html. If you don't recognize the file extension, just use the MIME type text/plain.

In addition to Content-Type, send back a Content-Length header that indicates the length of the file to follow, as in:

HTTP/1.1 200 OK\r\n
Content-Length: 92\r\n
Content-Type: image/gif\r\n\r\n
Lastly, create a FileInputStream for the File returned by getFile(), and wraps the FileInputStream in a BufferedInputStream. Then read bytes from the file and write them to the socket. When your done, just close both the socket and the file, and return from the run() method.

Sponsored Links

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use