Java - Cliente-Servidor

 
Vista:

Cliente-Servidor

Publicado por Dark (12 intervenciones) el 12/06/2023 06:00:10
Hola buenas noches tengo que diseñar e implementar una arquitectura Cliente-Servidor (modificada) con Sockets, RPC y RMI en la que el Servidor sea capaz de atender varias solicitudes de múltiples Clientes los
cuales solicitan, desde consola o mediante una GUI, conocer los lugares turísticos de una
Ciudad que el Cliente solicita y dicha ciudad es mostrada en un mapa.

Aqui tengo mis codigos de rpc, rmi y socket que pide pero no se como juntarlos para que sea solo una clase servidor y una cliente junto con mi clase de los. lugares turísticos o no se si sea posible hacerlo con solo una clase cliente y una servidor junto con mi clase lugares, no se si me podrían apoyar en como resolver este problema y como podría hacer que muestre los lugares en un mapa de google.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
Socket
 
Clase Cliente:
 
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
 *
 *
 */
public class Cliente {
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
        Socket cliente = new Socket("localhost",8080);
 
 
        //Variables para la entrada y escritura del cliente
        BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in));
        BufferedReader lecturaCliente = new BufferedReader(new InputStreamReader(cliente.getInputStream()));
        PrintWriter escrituraCliente = new PrintWriter(cliente.getOutputStream(),true);
        DataInputStream in = new DataInputStream(cliente.getInputStream());
 
        //Creacion de la variable mensajeCliente
        String mensajeCliente = new String();
 
        //Lectura de lo que contenga la variable
        mensajeCliente = lecturaCliente.readLine();
        System.out.println(mensajeCliente);
 
        //Condicional para salir o escribir el nombre de alguna otra ciudad
        while(true){
            String mensaje = entrada.readLine();
            escrituraCliente.println(mensaje);
            if(mensaje.equals("salir")){
            break;
            }
            else{
            String mensajeR = in.readUTF();
                System.out.println(mensajeR);
                        System.out.println("Escribe el nombre de otra ciudad si desea seguir conociendo lugares turisticos o 'salir' para terminar conexion");
 
            }
 
        }
        //Imprimir el mensaje del cliente y cerrar el cliente al finalizar el programa
        mensajeCliente = lecturaCliente.readLine();
        System.out.println(mensajeCliente);
        cliente.close();
    }
 
}
 
 
Clase Lugares:
 
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.net.Socket;
import java.util.Scanner;
/**
 *
 *
 */
 
//Clase en la que estaran los diferentes lugares
public class Lugares extends Thread {
    Socket clienteConectado;
    int id;
 
    public Lugares(Socket clienteConectado, int id) {
        this.clienteConectado = clienteConectado;
        this.id = id;
    }
 
 
    //Metodo run que obtiene los diferentes mensajes del cliente
    public void run(){
        BufferedReader lecturaServidor = null;
        DataOutputStream out = null;
 
        try {
            String[][] datos = LeerArchivo();
 
            lecturaServidor = new BufferedReader(new InputStreamReader(clienteConectado.getInputStream()));
            String mensajeRecibido = new String();
            out = new DataOutputStream(clienteConectado.getOutputStream());
            PrintWriter escrituraServidor = new PrintWriter(clienteConectado.getOutputStream(),true);
 
            System.out.println("Esperando mensaje....");
 
            try {
                escrituraServidor.println("Ingresa el nombre de una ciudad para conocer sus lugares turisticos o 'salir' para terminar sesion");
 
                while(!(mensajeRecibido = lecturaServidor.readLine()).equals("salir")){
                    System.out.println("Mensaje recibido del cliente "+ clienteConectado.getRemoteSocketAddress() + " :"+ mensajeRecibido );
                    int i = 0;
                    String lugar = null;
                        if(!mensajeRecibido.equalsIgnoreCase("salir")){
                            while(i < datos.length){
                                if (datos[i][0].equalsIgnoreCase(mensajeRecibido)){
 
                                 lugar = "Lugares Turisticos: " + datos[i][1];
                                 break;
                                }  else {
                                    lugar ="Ciudad no encontrada";
                                }
                                i++;
                            }
                            out.writeUTF(lugar);
                        }
                }
 
                escrituraServidor.println("Sesion terminada");
                clienteConectado.close();
                System.out.println("Conexion con el cliente: "+ clienteConectado.getRemoteSocketAddress() + " terminada.");
 
 
            } catch (IOException e) {
                Logger.getLogger(Lugares.class.getName()).log(Level.SEVERE,null,e);
            }
 
        } catch (IOException e) {
            Logger.getLogger(Lugares.class.getName()).log(Level.SEVERE,null,e);
        }
        try {
            lecturaServidor.close();
        } catch (IOException e) {
          Logger.getLogger(Lugares.class.getName()).log(Level.SEVERE,null,e);
 
        }
    }
 
    //Metodo para leer el archivo que contiene los diferentes lugares
    public static String[][] LeerArchivo() throws FileNotFoundException, IOException{
 
        File archivo = new File("lugares.txt");
        FileReader fr = new FileReader(archivo);
        BufferedReader br = new BufferedReader(fr);
 
        String linea;
        int nlinea = 0, i = 0;
 
        Scanner sc = new Scanner(archivo);
 
        while(sc.hasNextLine()) {
            sc.nextLine();
            nlinea++;
        }
        String[][] datos = new String[nlinea][2];
 
        while ((linea = br.readLine())!=null){
            String[] temp = linea.split(";");
            datos[i][0] = temp[0];
            datos[i][1] = temp[1];
            i++;
        }
 
        fr.close();
        return datos;
 
    }
 
}
 
Clase Servidor
 
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
 *
 *
 */
public class Servidor {
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // Creacion del servidor y conexion con el o los cliente
        try {
            ServerSocket servidor = new ServerSocket(8080);
            System.out.println("Servidor Iniciado");
            int i=1;
 
            while (true){
                Socket clienteConectado = servidor.accept();
                System.out.println("Cliente conectado con direccion: "+clienteConectado.getRemoteSocketAddress());
                Lugares clienteEntrante = new Lugares(clienteConectado,i);
                Thread hilo = new Thread(clienteEntrante);
                hilo.start();
                i++;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
 
}
 
RPC
 
Clase Cliente
 
import java.util.Scanner;
import java.util.Vector;
import org.apache.xmlrpc.XmlRpcClient;
 
 
public class Cliente {
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        try {
            XmlRpcClient client = new XmlRpcClient("http://localhost/");
            Vector params = new Vector();
            Scanner sc = new Scanner(System.in);
            String ent = "" , sal = "";
            System.out.println("Conectado al servidor");
 
            System.out.println("Escriba un identificador para el cliente");
            String id = sc.nextLine();
            params.addElement(id);
 
            Object result = client.execute("miServer.Inicio", params);
            System.out.println(result.toString());
 
            while (!sal.equals("salir")){
 
                params.clear();
                ent = sc.nextLine();
                params.addElement(id);
                params.addElement(ent);
 
                result = client.execute("miServer.Buscar", params);
 
                sal = result.toString();
                System.out.println(sal);
                System.out.println("Escribe el nombre de otra ciudad o 'salir' para terminar conexion");
 
            }
 
            System.out.println("Conexion terminada");
 
        } catch (Exception e) {
            System.out.println("JavaClient: "+ e);
        }
        }
    }
 
Clase Lugares
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
 
 
 
public class Lugares  {
 
 
    public String Inicio(String id){
        System.out.println("Cliente con id "+ id + " conectado");
        return "Ingresa el nombre de una ciudad para conocer sus lugares turisticos o 'salir' para terminar sesion ";
    }
 
    public String Buscar(String id, String cEnt)throws IOException{
    String[][] datos = LeerArchivo();
 
    System.out.println("Mensaje recibido del cliente con ID: "+ id +" : "+cEnt);
    int i = 0;
    String cSal = null;
    if(!cEnt.equalsIgnoreCase("salir")){
        while(i < datos.length){
            if(datos[i][0].equalsIgnoreCase(cEnt)){
                cSal="Lugares turisticos: " + datos[i][1];
                break;
            }  else {
                cSal="Ciudad no encontrada";
            }
            i++;
        }
 
    }
    else{
        System.out.println("El cliente con ID: "+ id + " finalizo sesion");
        cSal="salir";
    }
    return cSal;
}
 
 
 
 
public static String[][] LeerArchivo() throws FileNotFoundException, IOException{
 
    File archivo = new File("lugares.txt");
    FileReader fr = new FileReader(archivo);
    BufferedReader br = new BufferedReader(fr);
 
    String linea;
    int nlinea = 0, i = 0;
 
    Scanner sc = new Scanner(archivo);
 
    while(sc.hasNextLine()) {
        sc.nextLine();
        nlinea++;
    }
    String[][] datos = new String[nlinea][2];
 
    while ((linea = br.readLine())!=null){
        String[] temp = linea.split(";");
        datos[i][0] = temp[0];
        datos[i][1] = temp[1];
        i++;
    }
 
    fr.close();
    return datos;
 
    }
 
}
 
Clase Servidor
 
import org.apache.xmlrpc.WebServer;
 
 
public class Servidor {
    /**
     * @param args the command line arguments
     */
 
    public static void main(String[] args) {
        // TODO code application logic here
        try {
            System.out.println("Iniciando XML-RPC Server...");
            WebServer server = new WebServer(80);
            Lugares lugares = new Lugares();
            server.addHandler("miServer", lugares);
 
            server.start();
 
            System.out.println("Inicio exitoso del servidor, queda en espera de peticiones del cliente...");
 
        } catch (Exception exception) {
            System.out.println("JavaServer " + exception);
        }
 
    }
}
 
 
RMI
 
Clase Cliente
 
import java.io.IOException;
import java.util.Scanner;
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
 
public class Cliente {
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
        try {
            Registry miRegistro = LocateRegistry.getRegistry("localhost",1099);
            Interface i = (Interface) miRegistro.lookup("Lugares");
 
            Scanner sc = new Scanner(System.in);
            System.out.println("Escriba un identificador para el cliente");
            String id = sc.nextLine();
            System.out.println(i.Inicio(id));
 
            String ent = " " ,sal = " ";
 
            while (!sal.equals("salir")){
                ent = sc.nextLine();
                sal = i.Buscar(id, ent);
                System.out.println(sal);
                System.out.println("Escriba el nombre de otra ciudad o 'salir' para terminar conexion");
 
            }
 
            System.out.println("Conexion finalizada");
 
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        }
    }
Clase Interface
 
import java.rmi.Remote;
 
 
public interface Interface extends Remote{
    public String Buscar(String id, String maIN) throws Exception;
    public String Inicio(String id) throws Exception;
 
}
 
 
Clase Lugares
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Scanner;
 
public class Lugares extends UnicastRemoteObject implements Interface  {
 
    public Lugares() throws Exception{
        super();
    }
 
    public String Inicio(String id){
        System.out.println("Cliente con id "+ id + " conectado");
        return "Escriba el nombre de la ciudad o 'salir' para finalizar sesion ";
    }
 
    public String Buscar(String id, String cEnt)throws IOException{
    String[][] datos = LeerArchivo();
 
    System.out.println("Mensaje recibido del cliente con ID: "+ id +" : "+cEnt);
    int i = 0;
    String cSal = null;
    if(!cEnt.equalsIgnoreCase("salir")){
        while(i < datos.length){
            if(datos[i][0].equalsIgnoreCase(cEnt)){
                cSal="Lugares turisticos: " + datos[i][1];
                break;
            }  else {
                cSal="Ciudad no encontrada";
            }
            i++;
        }
 
    }
    else{
        System.out.println("El cliente con ID: "+ id + " finalizo sesion");
        cSal="salir";
    }
    return cSal;
}
 
 
 
 
public static String[][] LeerArchivo() throws FileNotFoundException, IOException{
 
    File archivo = new File("lugares.txt");
    FileReader fr = new FileReader(archivo);
    BufferedReader br = new BufferedReader(fr);
 
    String linea;
    int nlinea = 0, i = 0;
 
    Scanner sc = new Scanner(archivo);
 
    while(sc.hasNextLine()) {
        sc.nextLine();
        nlinea++;
    }
    String[][] datos = new String[nlinea][2];
 
    while ((linea = br.readLine())!=null){
        String[] temp = linea.split(";");
        datos[i][0] = temp[0];
        datos[i][1] = temp[1];
        i++;
    }
 
    fr.close();
    return datos;
 
    }
 
}
 
 
Clase Servidor
 
import java.io.IOException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
 
 
public class Servidor {
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException{
        // TODO code application logic here
        try {
            Registry registro = LocateRegistry.createRegistry(1099);
            registro.bind("Lugares", new Lugares());
 
            System.out.println("Servidor funcionando");
 
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
 
    }
 
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder