1
+
2
+ import java .net .*;
3
+ import java .util .Date ;
4
+ import java .io .*;
5
+
6
+ public class QuoteServerThread extends Thread {
7
+ protected DatagramSocket socket = null ;
8
+ protected BufferedReader in = null ;
9
+ protected Boolean moreQuotes = true ;
10
+
11
+ public QuoteServerThread () throws IOException {
12
+ this ("QuoteServerThread" );
13
+ }
14
+
15
+ public QuoteServerThread (String name ) throws IOException {
16
+ super (name );
17
+ socket = new DatagramSocket (4445 );
18
+
19
+ try {
20
+ in = new BufferedReader (new FileReader ("one-liniers.txt" ));
21
+ } catch (FileNotFoundException e ) {
22
+ System .err .println ("No podemos abrir el archivo. Server time en cambio." );
23
+ }
24
+ }
25
+
26
+ public void run (){
27
+ while (moreQuotes ){
28
+ try {
29
+ byte [] buf = new byte [256 ];
30
+ //recibir datagrama
31
+ DatagramPacket packet = new DatagramPacket (buf , buf .length );
32
+ socket .receive (packet );
33
+
34
+ //resolver y enviar respuesta
35
+ String dString = null ;
36
+ if (in == null ){
37
+ dString = new Date ().toString ();
38
+ } else {
39
+ dString = getNextQuote ();
40
+ }
41
+
42
+ buf = dString .getBytes ();
43
+
44
+ //debemos enviar la respuesta al cliente
45
+ // se debe saber dirección del cliente y puerto desde donde llegó
46
+ // la request
47
+ InetAddress iAddress = packet .getAddress ();
48
+ int port = packet .getPort ();
49
+ packet = new DatagramPacket (buf , buf .length ,iAddress ,port );
50
+ socket .send (packet );
51
+ } catch (IOException e ) {
52
+ e .printStackTrace ();
53
+ moreQuotes = false ;
54
+ }
55
+ }
56
+ }
57
+
58
+ protected String getNextQuote (){
59
+ String returnValue = null ;
60
+ try {
61
+ if ((returnValue = in .readLine ()) == null ){
62
+ in .close ();
63
+ moreQuotes = false ;
64
+ returnValue = "No more Quotes, Good Bye" ;
65
+ }
66
+ } catch (IOException e )
67
+ {
68
+ returnValue = "IOException en obtener nueva cita en servidor" ;
69
+ }
70
+ return returnValue ;
71
+ }
72
+
73
+ }
0 commit comments