What is a Socket

download What is a Socket

of 13

Transcript of What is a Socket

  • 7/30/2019 What is a Socket

    1/13

    What is a socket?

    Normally, a server runs on a specific computer and has a socket that is bound to aspecific port number. The server just waits, listening to the socket for a client to

    make a connection request.On the client-side: The client knows the hostname of the machine on which theserver is running and the port number on which the server is listening. To make aconnection request, the client tries to rendezvous with the server on the server'smachine and port. The client also needs to identify itself to the server so it binds toa local port number that it will use during this connection. This is usually assignedby the system.

    If everything goes well, the server accepts the connection. Upon acceptance, theserver gets a new socket bound to the same local port and also has its remoteendpoint set to the address and port of the client. It needs a new socket so that itcan continue to listen to the original socket for connection requests while tending tothe needs of the connected client.

    On the client side, if the connection is accepted, a socket is successfully createdand the client can use the socket to communicate with the server.

    The client and server can now communicate by writing to or reading from theirsockets.

    Definition:A socket is one endpoint of a two-way communication link between two programsrunning on the network. A socket is bound to a port number so that the TCP layercan identify the application that data is destined to be sent.

    An endpoint is a combination of an IP address and a port number. Every TCPconnection can be uniquely identified by its two endpoints. That way you can havemultiple connections between your host and the server.

  • 7/30/2019 What is a Socket

    2/13

    Scenario

    Server:Host: joss-PC

    Port TCP: 9999Port UDP: 5557

    Client:Host: Juanjose-PC

    Port TCP: 9999Port UDP: 5557

    Code

    Class Escoje

    import java.io.*;/*** Write a description of class ok here.

    ** @author (your name)* @version (a version number or a date)*/public class Escoje{

    public static void main (String args[])throws IOException{

    int a;BufferedReader entrada = new BufferedReader (new

    InputStreamReader(System.in));System.out.println("Elije que el tipo de aplicacin deseas...");System.out.println("");System.out.println("1.-TCP");System.out.println("2.-UDP");a=Integer.parseInt(entrada.readLine());if (a ==1){

  • 7/30/2019 What is a Socket

    3/13

    System.out.println("SE EJECUTAR EL SERVIDOR DE TCP");new ServidorTcp();

    }elseSystem.out.println("EL SERVIDOR UCP SE EST EJECUTANDO");

    new ServidorUdp();}

    }

    Socket TCP

    Serverimport java.lang.*;import java.io.*;import java.net.*;

    class Server1 {public static void main(String args[]) {

    String data = "Cliente, llamando al cliente!";try {

    ServerSocket srvr = new ServerSocket(9999);Socket skt = srvr.accept();System.out.print("Se ha establecido la conexin!\n");PrintWriter out = new PrintWriter(skt.getOutputStream(), true);System.out.print("Enviando mensaje: '" + data + "'\n");out.print(data);

    out.close();skt.close();srvr.close();

    }catch(Exception e) {

    System.out.print("Whoops! Algo anda mal!\n");}

    }}

    Client

    import java.lang.*;import java.io.*;import java.net.*;

    class Client {

  • 7/30/2019 What is a Socket

    4/13

    public static void main(String args[]) {try {

    Socket skt = new Socket("joss-PC", 9999);BufferedReader in = new BufferedReader(new

    InputStreamReader(skt.getInputStream()));

    System.out.print("Recibiendo mensaje: '");while (!in.ready()) {}System.out.println(in.readLine()); // Read one line and output it

    System.out.print("'\n");in.close();

    }catch(Exception e) {

    System.out.print("Whoops! Algo no est funcionando!\n");}

    }}

    Socket UDP

    Server

    import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;

    /*** Servidor de udp que se pone a la escucha de DatagramPacket que contengan* dentro DatoUdp y los escribe en pantalla.*/public class ServidorUdp{

    /*** Prueba del prorama ServidorUdp*

    * @param args*/public static void main(String[] args){

    new ServidorUdp();}

    /**

  • 7/30/2019 What is a Socket

    5/13

    * Crea una instancia de esta clase, poniendose a la escucha del puerto* definido en Constantes y escribe en pantalla todos los mensajes que le* lleguen.*/public ServidorUdp()

    { System.out.println("EJECUTANDO SERVIDOR");try{

    // La IP es la local, el puerto es en el que el servidor est// escuchando.DatagramSocket socket = new DatagramSocket(

    Constantes.PUERTO_DEL_SERVIDOR, InetAddress.getByName("joss-PC"));

    // Un DatagramPacket para recibir los mensajes.DatagramPacket dato = new DatagramPacket(new byte[100], 100);

    // Bucle infinito.while (true){

    // Se recibe un dato y se escribe en pantalla.socket.receive(dato);System.out.print("Recibido dato de "

    + dato.getAddress().getHostName() + " : ");

    // Conversion de los bytes a DatoUdpDatoUdp datoRecibido = DatoUdp.fromByteArray(dato.getData());System.out.println(datoRecibido.cadenaTexto);

    }} catch (Exception e){

    e.printStackTrace();}

    }}

    Client

    import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;

    /*** Abre un socket udp y enva por l 10 mensajes consistentes en 10 clases

  • 7/30/2019 What is a Socket

    6/13

    * DatoUdp.*/public class ClienteUdp{

    /*** Programa de prueba. Instancia esta clase* @param args*/public static void main(String[] args){

    new ClienteUdp();}

    /*** Crea una instancia de esta clase y enva los 10 mensajes**/public ClienteUdp(){

    aleatorio A = new aleatorio();int aa = A.geta();System.out.println("Puerto Aleatorio # :" + aa);

    try{

    // La IP es la local, el puerto es en el que este cliente est// escuchando.DatagramSocket socket = new DatagramSocket(

    Constantes.PUERTO_DEL_CLIENTE, InetAddress.getByName("Juanjose-PC"));

    // Se instancia un DatoUdp y se convierte a bytes[]DatoUdp elDato = new DatoUdp("hola servidor");byte[] elDatoEnBytes = elDato.toByteArray();

    // Se meten los bytes en el DatagramPacket, que es lo que se// va a enviar por el socket.// El destinatario es el servidor.// El puerto es por el que est escuchando el servidor.DatagramPacket dato = new DatagramPacket(elDatoEnBytes,

    elDatoEnBytes.length, InetAddress.getByName(Constantes.HOST_SERVIDOR),

    Constantes.PUERTO_DEL_SERVIDOR);

    // Se enva el DatagramPacket 10 veces, esperando 1 segundo entre// envo y envo.

  • 7/30/2019 What is a Socket

    7/13

    for (int i = 0; i < 10; i++){

    System.out.println("Envio dato " + i);socket.send(dato);Thread.sleep(1000);

    }} catch (Exception e){

    e.printStackTrace();}

    }}

    Class Constantes

    /** Constantes para el ejemplo de envo y recepcin con socket udp. */

    public class Constantes{/** Puerto en el que escucha el servidor. */public static final int PUERTO_DEL_SERVIDOR=5557;

    /** Puerto en el que escucha el cliente */public static final int PUERTO_DEL_CLIENTE=5558;

    /** Host en el que est el servidor */public static final String HOST_SERVIDOR="joss-PC";

    /** Host en el que est el cliente */public static final String HOST_CLIENTE="Juanjose-PC";}

    Class DatoUDP

    import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;

    public class DatoUdp implements Serializable

  • 7/30/2019 What is a Socket

    8/13

    {/*** serial uid*/private static final long serialVersionUID = 3258698714674442547L;

    /*** Crea una instancia de la clase, guardando la cadena que se le pasa.* @param cadena*/public DatoUdp (String cadena){

    this.cadenaTexto=cadena;}public String cadenaTexto;

    /*** Se autoconvierte esta clase a array de bytes.* @return La clase convertida a array de bytes.*/public byte [] toByteArray(){

    try{

    // Se hace la conversin usando un ByteArrayOutputStream y un// ObjetOutputStream.

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();ObjectOutputStream os = new ObjectOutputStream (bytes);os.writeObject(this);os.close();return bytes.toByteArray();

    }catch(Exception e){

    e.printStackTrace();return null;

    }}

    /*** Se convierte el array de bytes que recibe en un objeto DatoUdp.* @param bytes El array de bytes* @return Un DatoUdp.*/public static DatoUdp fromByteArray (byte [] bytes){

    try

  • 7/30/2019 What is a Socket

    9/13

    {// Se realiza la conversin usando un ByteArrayInputStream y un// ObjectInputStreamByteArrayInputStream byteArray = new ByteArrayInputStream(bytes);ObjectInputStream is = new ObjectInputStream(byteArray);

    DatoUdp aux = (DatoUdp)is.readObject();is.close();return aux;

    }catch(Exception e){

    e.printStackTrace();return null;

    }}

    }

  • 7/30/2019 What is a Socket

    10/13

    Running the sockets

    UDP

    Server

    Client

  • 7/30/2019 What is a Socket

    11/13

    Wireshark

  • 7/30/2019 What is a Socket

    12/13

    TCP

    Server

    Client

  • 7/30/2019 What is a Socket

    13/13

    Wireshark