Вы находитесь на странице: 1из 15

UNIVERSIDAD CARLOS III DE MADRID DEPARTAMENTO DE INGENIERA TELEMTICA

Sockets para servidor


Daniel Daz Snchez Florina Almenrez Andrs Marn Departamento de Ingeniera Telemtica Universidad Carlos III de Madrid dds@it.uc3m.es

Contexto
Objetivos
Conocer las particularidades de las comunicaciones en Java Java, desarrollando pequeos programas que interacten con protocolos conocidos Conocer la perspectiva de servidor del paquete java de sockets

Comunicaciones: Socket, ServerSocket Pg. 1

ndice
Introduccin a los sockets de servidor Conceptos bsicos Sockets servidor
clase ServerSocket

Comunicaciones: Socket, ServerSocket Pg. 2

Introduccin a los sockets de servidor


Hasta ahora hemos visto los sockets de cliente pero un cliente
no es nada si no puede conectarse al servidor conoce el host/puerto al que quiere conectar sabe cuando realiza la conexin

En cambio, un servidor
No conoce de antemano quien va a conectarse Ni cuando

Un servidor es como un telefonista, siempre est esperando a que lleguen llamadas entrantes
Comunicaciones: Socket, ServerSocket Pg. 3

Introduccin a los sockets de servidor

Comunicaciones: Socket, ServerSocket Pg. 4

Introduccin a los sockets de servidor


En esta sesin veremos como hacer que un servidor espere una conexin entrante Cmo manejar dichas conexiones de forma concurrente
Muchos clientes pueden conectarse simultneamente al servidor

Veremos algunos ejemplos

Comunicaciones: Socket, ServerSocket Pg. 5

Conceptos bsicos: threads


Hasta ahora hemos trabajado con clientes, programas secuenciales con un solo hilo Los servidores soportan mltiples conexiones al mismo tiempo. Por tanto, debemos usar threads o hilos Para hacer un programa multihilo podemos hacer dos cosas:
Extender la clase java.lang.Thread Implementar el interfaz Runnable

En ambos casos, la funcionalidad del thread se implementa en el mtodo run. Veamos un ejemplo
Comunicaciones: Socket, ServerSocket Pg. 6

Conceptos bsicos: threads


Ejemplo de threads con java.lang.Thread j p j g
publicclassEjemploConcurrencia1extendsThread{ /*enlosatributos,tendremostodoaquelloquenecesitamosparaque *nuestrohilohagaloquedeseamos.Enestecaso,usamosunstring yunentero */ / String datoA; int datoB; public EjemploConcurrencia1(String nombreThread,String datoA,int datoB) { super(nombreThread);//ElnombredelThread this.datoA =datoA; this.datoB =datoB; } /*Todothread debetenerunmtodorun. *Estemtodosellamacuandocomienzaelthread*/ public void run(){ for (int i=datoB;i<1000;i++) System.out.println("Elthread denombre"+getName()+"conelmensaje"+datoA +"estcontando y p ( g () j "+i); //cuandotermina,escribimosunmensaje System.out.println("Elthread connombre"+getName()+"haterminado***************"); } publicstaticvoidmain(String[]args){ /*Creamosvarioshilosparaverelfuncionamiento*/ newEjemploConcurrencia1("uno","mensaje1",10).start(); newEjemploConcurrencia1("dos","mensaje2",20).start(); newEjemploConcurrencia1("tres","mensaje3",30).start(); System.out.println("Terminathread main"); } }

Comunicaciones: Socket, ServerSocket Pg. 7

Conceptos bsicos: threads


Ejemplo de threads con java.lang.Thread j p j g
dds@saml:~/workspace/ComputacionEnLaRed/bin$javacp . es.uc3m.it.gast.pervasive.teaching.networkComputing.ServerSockets.ex amples.EjemploConcurrencia1

Comunicaciones: Socket, ServerSocket Pg. 8

Conceptos bsicos: threads


Ejemplo de threads con java.lang.Thread j p j g
//HacemosquelaclaseimplementeRunnable public class EjemploConcurrencia2implements Runnable{ /*enlosatributos,tendremostodoaquelloquenecesitamosparaque *nuestrohilohagaloquedeseamos.Enestecaso,usamosunstring yunentero */ String nombreThread; String datoA; int datoB; public EjemploConcurrencia2(String nombreThread,String datoA,int datoB) { this.nombreThread =nombreThread; this.datoA =datoA; this.datoB =datoB; } /*Todothread debetenerunmtodorun. *Estemtodosellamacuandocomienzaelthread*/ public void run(){ Thread.currentThread().setName(nombreThread); for (int i=datoB;i<1000;i++) System.out.println("Elthread denombre"+Thread.currentThread().getName()+"conelmensaje"+datoA +" estcontando"+i); //cuandotermina,escribimosunmensaje System.out.println("Elthread connombre"+Thread.currentThread().getName()+"haterminado***************"); } publicstaticvoidmain(String[]args){ /*Creamosvarioshilosparaverelfuncionamiento*/ newThread(newEjemploConcurrencia2("uno","mensaje1",10)).start(); newThread(newEjemploConcurrencia2("dos","mensaje2",20)).start(); newThread(newEjemploConcurrencia2("tres","mensaje3",30)).start(); System.out.println("Terminathread main"); } }

Comunicaciones: Socket, ServerSocket Pg. 9

La clase ServerSocket
La clase Socket est en el paquete java.net
Proporciona soporte de TCP/IP Los constructores toman como parmetros:
El PUERTO consisten en un entero (int) entre 0-65535 Si la mquina donde se ejecuta el programa dispone de ms de un interfaz de red (ej. est conectada a la vez por cable y wifi), se puede especificar el interfaz que se debe usar para enviar/recibir datos (multihoming)

Las excepciones son de un tipo:


IOException: por errores de entrada y salida falta de permisos salida, permisos, interfaz de red erroneo BindException: cuando no se pude asociar a un puerto

Comunicaciones: Socket, ServerSocket Pg. 10

La clase ServerSocket
La clase ServerSocket nos ayuda a realizar el proceso de d conexin i
Instanciar ServerSocket Escuchar en el puerto (bind) ServerSocket escucha hasta que llega una conexin (accept) Cuando llega una conexin C g devuelve un objeto Socket

Comunicaciones: Socket, ServerSocket Pg. 11

La clase ServerSocket
En java el constructor hace las tareas de configurar el ServerSocket y escuchar S S k t h en el puerto
Instanciar ServerSocket Escuchar en el puerto (bind)

Comunicaciones: Socket, ServerSocket Pg. 12

La clase ServerSocket:Constructores
Java.net.ServerSocket

Constructor
publicServerSocket(intport)throwsBindException,IOException

Descripcin/Parmetros
Elconstructorcreaunsocketdeescucha(ServerSocket)enelpuerto indicado(creacin+bind).Sielparmetroes0javaseleccionar unpuertoaleatorio.Sielconstructorarrojaunaexcepcindetipo BindException (IOException)puedeserdebidoaqueelpuertoesten usooaquenotenemossuficientespermisos(puertosde0a1024)

Ejemplo
try{ ServerSocket servidorWeb =newServerSocket(80); } catch(IOException ex){ System.err.println(ex); } Comunicaciones: Socket, ServerSocket Pg. 13

La clase ServerSocket:Constructores
Escanear el PC p para ver los p puertos de escucha usados
package es.uc3m.it.gast.pervasive.teaching.networkComputing.ServerSockets.examples; import java.io.IOException; import java.net.ServerSocket; public class EscanerDeServidoresLocales { publicstaticvoidmain(String[]args){ /*compruebalospuertosdesdeel1al65535*/ ServerSocket test=null; for (int puerto=1;puerto<=65535;puerto++){ try{ //Sielservidorfallaenescucharenelpuertosignificaque //yahayunservidorendichopuerto // ya hay un servidor en dicho puerto test=newServerSocket(puerto); if (test!=null) test.close(); }catch(IOException ex){ System.out.println("Elpuerto"+puerto +"estocupadoporunservidor."); } } } } Comunicaciones: Socket, ServerSocket Pg. 14

La clase ServerSocket:Constructores
Java.net.ServerSocket

Constructor
publicServerSocket(intport,intqueueLength)throwsIOException, BindException

Descripcin/Parmetros
Elconstructorcreaunsocketdeescucha(ServerSocket)enelpuerto indicado.Sielparmetroes0javaseleccionarunpuerto aleatorio.Permiteindicarelnmerodeconexionesquesepueden guardarenlacola(sinaceptar)hastaqueelservidorcomienzaa rechazarconexiones.

Ejemplo
try{ ServerSocket glassfish =newServerSocket(4848,100); } catch(IOException ex){ System.err.println(ex); } Comunicaciones: Socket, ServerSocket Pg. 15

La clase ServerSocket:Constructores
MY HOST Network N k interface Ne Network k inte erface

Java.net.ServerSocket

Constructor

REMOTE HOST

publicServerSocket(intport,intqueueLength,InetAddressbindAddress) throwsBindException,IOException

Descripcin/Parmetros
Igualqueelanteriorperopermiteseleccionarelinterfazdered (direccinlocal)enelqueescuchar.Supongamosquetenemosvarias tarjetasdered,unawifi yotraethernet.

Ejemplo
try{ ServerSocket glassfish =newServerSocket(4848,100); } catch(IOException ex){ System.err.println(ex); } Comunicaciones: Socket, ServerSocket Pg. 16

La clase ServerSocket:Constructores
java.net.ServerSocket

Constructor
public ServerSocket()throws IOException publicvoidbind(SocketAddressendpoint)throws IOException publicvoidbind(SocketAddressendpoint,intqueueLength)throws IOException

Descripcin/Parmetros
Enestecaso,simplementecrealaclase.Habraquehacerbind manualmente(usandobind)paraqueescucharaenelpuerto.

Ejemplo
ServerSocket ss =newServerSocket(); //setsocketoptions... SocketAddress http=newInetSocketAddress(80); ss.bind(http);

Comunicaciones: Socket, ServerSocket Pg. 17

La clase ServerSocket
El siguiente paso es esperar a una conexin y cuando ll d llegue aceptarla t l El mtodo accept es bloqueante, es decir, una vez se llama, el programa se detiene hasta que llega una conexin

Comunicaciones: Socket, ServerSocket Pg. 18

La clase ServerSocket:mtodo accept


java.net.ServerSocket

Mtodo
publicSocketaccept()throwsIOException

Descripcin/Parmetros
Unavezelsocketestconfiguradoyescuchando(bind)elmtodoaccept bloqueaelflujodelprogramahastaquellegaunaconexin. Elmtodoaccept devuelveunsocketcuandorecibeunaconexin.A partirdeahsepuedellamaragetInputStream ygetOutputStream paraobtenerlosstreams decomunicacinconelcliente.

Comunicaciones: Socket, ServerSocket Pg. 19

10

La clase ServerSocket:mtodo accept


Ejemplo j p
//CreounServerSocket enelpuerto8080 ServerSocket server = new ServerSocket(8080); server=newServerSocket(8080); //Llegadosaestepunto,sinoselanzanexcepcioneselServerSocket estconfigurado yescuchando(bind) //Bucleparaescucharconexionesentrantes while (true){ //alllamaraaccept sebloquea.Cuandollegaunaconexindevuelve unsocket Socketconexion =server.accept(); //enviamosdatos OutputStreamWriter out p =newOutputStreamWriter(conexion.getOutputStream()); out.write(Tehasconectadoalservido,hastaluego\r\n"); //yahemosatendidoalcliente,cerramoselsocket(noel serverSocket) connection.close(); }
Comunicaciones: Socket, ServerSocket Pg. 20

La clase ServerSocket
Cuando se acepta, obtiene un Socket se

Para enviar y recibir datos se procede como en la clase socket

Comunicaciones: Socket, ServerSocket Pg. 21

11

La clase ServerSocket: mtodos


Getters: obtener informacin sobre el ServerSocket Cierre del ServerSocket Setters: Opciones de ServerSockets

Comunicaciones: Socket, ServerSocket Pg. 22

La clase ServerSocket: mtodos getters


java.net.ServerSocket

Mtodos
publicInetAddressgetInetAddress() publicintgetLocalPort()

Descripcin/Parmetros
getInetAddress devuelveladireccinlocal(interfazdered)enlaque escuchaelservidor. getLocalPort devuelveelpuertoenelqueescuchaelservidor(util si sehasolicitadounpuertoaleatorio)

Comunicaciones: Socket, ServerSocket Pg. 23

12

La clase ServerSocket: mtodos getters


Ejemplo j p
importjava.net.*; p j ; importjava.io.*; publicclassRandomPort { publicstaticvoidmain(String[]args){ try{ //solicitamos unpuerto aleatorio ServerSocket server=newServerSocket(0); System.out.println(Elsistema nos hadadoelpuerto + server.getLocalPort()); } catch(IOException ex){ System.err.println(ex); } } }
Comunicaciones: Socket, ServerSocket Pg. 24

La clase ServerSocket: mtodos getters


java.net.ServerSocket

Mtodos avanzados
publicintgetSoTimeout()throws IOException publicbooleangetReuseAddress()throws SocketException publicintgetReceiveBufferSize()throwsSocketException

Descripcin/Parmetros
getSoTimeout devuelveelvalordelavariabledesistemaTCPSO_TIMEOUT quecorrespondealtiempoesperadoporaccept antesdedevolver java.io.InterruptedIOException.Porlogeneralesinfinito. getReuseAddress devuelve el true/false (variable de sistema TCP devuelveeltrue/false(variabledesistemaTCP SO_TIMEOUT) indicandosiladireccin/pruerto puedereutilizarsesi aunexistetrficoatravesandolared(delaantiguaconexinque usabaelpuerto) getReceiveBufferSize devuelveelvalordelavariabledesistemaTCP SO_RCVBUF quecorrespondealtamaodelbufferderecepcinasignado acadasoket devueltoporaccept.Dependedelaplataforma.
Comunicaciones: Socket, ServerSocket Pg. 25

13

La clase ServerSocket:mtodo Close


java.net.ServerSocket

Mtodo
publicvoidclose()throwsIOException

Descripcin/Parmetros
Cierraelsocketdeservidor(ServerSocket).Deestamaneraelservidor dejadeescucharenelpuerto. Nodebeconfundirseconcerrarelsocketdevueltoporaccept.

Ejemplo
ServerSocket server=newServerSocket(80); server.close();

Comunicaciones: Socket, ServerSocket Pg. 26

La clase ServerSocket: mtodos setters


java.net.ServerSocket

Mtodos
publicvoidsetSoTimeout(inttimeout)throws SocketException publicvoidsetReuseAddress(booleanon)throwsSocketException public voidsetReceiveBufferSize(intsize)throwsSocketException

Descripcin/Parmetros
setSoTimeout asignaelvalordelavariabledesistemaTCPSO_TIMEOUT quecorrespondealtiempoesperadoporaccept antesdedevolver java.io.InterruptedIOException. setReuseAddress estableceelvalor(true/false)delavariablede sistemaTCPSO_TIMEOUT.Sielvalorestrue,ladireccin/pruerto i i i i puedereutilizarseaunenpresenciadetrficodelaantigua conexinqueusabaelpuerto. setReceiveBufferSize configuraeltamaodelbufferderecepcindel socketdevueltoporaccept.CorrespondealavariabledesistemaTCP SO_RCVBUF.
Comunicaciones: Socket, ServerSocket Pg. 27

14

La clase ServerSocket: ejemplo


Ejemplo: servidor de eco no concurrente j p
Unservidordeecorespondealclienteconlosmismosdatos questehaenviado. t h i d Vamosaconstruirunservidordeeconoconcurrente,es decirsolosoportaunclientesimultneo Elservidorsoportanicamentetexto. Pasos: 1.CrearelServerSocket 2.Escucharenelpuerto 3.Aceptarconexin i 4.Recibirdatos 5.Devolverlosdatosrecibidos

Comunicaciones: Socket, ServerSocket Pg. 28

15

Вам также может понравиться