You are on page 1of 13

What is a socket?

Normally, a server runs on a specific computer and has a socket that is bound to a specific 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 the server is running and the port number on which the server is listening. To make a connection request, the client tries to rendezvous with the server on the server's machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system.

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

On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server. The client and server can now communicate by writing to or reading from their sockets. Definition: A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquely identified by its two endpoints. That way you can have multiple connections between your host and the server.

Scenario

Server: Host: joss-PC Port TCP: 9999 Port UDP: 5557

Client: Host: Juanjose-PC Port TCP: 9999 Port 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) {

System.out.println("SE EJECUTAR EL SERVIDOR DE TCP"); new ServidorTcp(); } else System.out.println("EL SERVIDOR UCP SE EST EJECUTANDO"); new ServidorUdp(); } }

Socket TCP Server


import 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 {

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(); } /**

* 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 DatoUdp DatoUdp 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

* 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.

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

{ /** * 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

{ // Se realiza la conversin usando un ByteArrayInputStream y un // ObjectInputStream ByteArrayInputStream 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; } } }

Running the sockets


UDP Server

Client

Wireshark

TCP Server

Client

Wireshark

You might also like