Biblioteca Java - Blame information for rev 3

Subversion Repositories:
Rev:
Rev Author Line No. Line
3 mihai 1 /*
2  * QuoteServerThread.java
3  */
4 package lab.scd.net.datagrame;
5  
6 /**
7  * Class created by @author Mihai HULEA at Feb 23, 2005.
8  *
9  * This class is part of the laborator2_sockettest project.
10  *
11  */
12 import java.io.*;
13 import java.net.*;
14 import java.util.*;
15  
16 public class QuoteServerThread extends Thread {
17  
18     protected DatagramSocket socket = null;
19     protected BufferedReader in = null;
20     protected boolean moreQuotes = true;
21  
22     public QuoteServerThread() throws IOException {
23         this("QuoteServerThread");
24     }
25  
26     public QuoteServerThread(String name) throws IOException {
27         super(name);
28         socket = new DatagramSocket(4445);
29  
30         try {
31             in = new BufferedReader(new FileReader("one-liners.txt"));
32         } catch (FileNotFoundException e) {
33             System.err.println("Could not open quote file. Serving time instead.");
34         }
35     }
36  
37     public void run() {
38  
39         while (moreQuotes) {
40             try {
41                 byte[] buf = new byte[256];
42  
43                     // receive request
44                 DatagramPacket packet = new DatagramPacket(buf, buf.length);
45                 socket.receive(packet);
46  
47                     // figure out response
48                 String dString = null;
49                 if (in == null)
50                     dString = new Date().toString();
51                 else
52                     dString = getNextQuote();
53                 buf = dString.getBytes();
54  
55                     // send the response to the client at "address" and "port"
56                 InetAddress address = packet.getAddress();
57                 int port = packet.getPort();
58                 packet = new DatagramPacket(buf, buf.length, address, port);
59                 socket.send(packet);
60             } catch (IOException e) {
61                 e.printStackTrace();
62                 moreQuotes = false;
63             }
64         }
65         socket.close();
66     }
67  
68     protected String getNextQuote() {
69         String returnValue = null;
70         try {
71             if ((returnValue = in.readLine()) == null) {
72                 in.close();
73                 moreQuotes = false;
74                 returnValue = "No more quotes. Goodbye.";
75             }
76         } catch (IOException e) {
77             returnValue = "IOException occurred in server.";
78         }
79         return returnValue;
80     }
81  
82     public static void main(String[] args){
83         try {
84             QuoteServerThread srv  = new QuoteServerThread("test");
85             srv.start();
86         } catch (IOException e) {
87             e.printStackTrace();
88         }
89     }
90 }