Una guía para Java Sockets

1. Información general

El término programación de socket se refiere a la escritura de programas que se ejecutan en múltiples computadoras en las que los dispositivos están conectados entre sí mediante una red.

Hay dos protocolos de comunicación que se pueden utilizar para la programación de sockets: Protocolo de datagramas de usuario (UDP) y Protocolo de control de transferencia (TCP) .

La principal diferencia entre los dos es que UDP no tiene conexión, lo que significa que no hay sesión entre el cliente y el servidor, mientras que TCP está orientado a la conexión, lo que significa que primero se debe establecer una conexión exclusiva entre el cliente y el servidor para que tenga lugar la comunicación.

Este tutorial presenta una introducción a la programación de sockets en redes TCP / IP y demuestra cómo escribir aplicaciones cliente / servidor en Java. UDP no es un protocolo convencional y, como tal, es posible que no se encuentre a menudo.

2. Configuración del proyecto

Java proporciona una colección de clases e interfaces que se encargan de los detalles de comunicación de bajo nivel entre el cliente y el servidor.

Estos se encuentran principalmente en el paquete java.net , por lo que debemos realizar la siguiente importación:

import java.net.*;

También necesitamos el paquete java.io que nos brinda flujos de entrada y salida para escribir y leer mientras nos comunicamos:

import java.io.*;

En aras de la simplicidad, ejecutaremos nuestros programas cliente y servidor en la misma computadora. Si tuviéramos que ejecutarlos en diferentes computadoras en red, lo único que cambiaría es la dirección IP, en este caso, usaremos localhost en 127.0.0.1 .

3. Ejemplo simple

Ensuciemos nuestras manos con los ejemplos más básicos que involucran a un cliente y un servidor . Será una aplicación de comunicación bidireccional donde el cliente saluda al servidor y el servidor responde.

Creemos la aplicación del servidor en una clase llamada GreetServer.java con el siguiente código.

Incluimos el método principal y las variables globales para llamar la atención sobre cómo ejecutaremos todos los servidores en este artículo. En el resto de los ejemplos de los artículos, omitiremos este tipo de código más repetitivo:

public class GreetServer { private ServerSocket serverSocket; private Socket clientSocket; private PrintWriter out; private BufferedReader in; public void start(int port) { serverSocket = new ServerSocket(port); clientSocket = serverSocket.accept(); out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String greeting = in.readLine(); if ("hello server".equals(greeting)) { out.println("hello client"); } else { out.println("unrecognised greeting"); } } public void stop() { in.close(); out.close(); clientSocket.close(); serverSocket.close(); } public static void main(String[] args) { GreetServer server=new GreetServer(); server.start(6666); } }

También creemos un cliente llamado GreetClient.java con este código:

public class GreetClient { private Socket clientSocket; private PrintWriter out; private BufferedReader in; public void startConnection(String ip, int port) { clientSocket = new Socket(ip, port); out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); } public String sendMessage(String msg) { out.println(msg); String resp = in.readLine(); return resp; } public void stopConnection() { in.close(); out.close(); clientSocket.close(); } }

Iniciemos el servidor; en su IDE, puede hacer esto simplemente ejecutándolo como una aplicación Java.

Y ahora enviemos un saludo al servidor mediante una prueba unitaria, que confirma que el servidor en realidad envía un saludo en respuesta:

@Test public void givenGreetingClient_whenServerRespondsWhenStarted_thenCorrect() { GreetClient client = new GreetClient(); client.startConnection("127.0.0.1", 6666); String response = client.sendMessage("hello server"); assertEquals("hello client", response); }

No se preocupe si no comprende completamente lo que está sucediendo aquí, ya que este ejemplo está destinado a darnos una idea de qué esperar más adelante en el artículo.

En las siguientes secciones, analizaremos la comunicación de socket utilizando este ejemplo simple y profundizaremos en los detalles con más ejemplos.

4. Cómo funcionan los enchufes

Usaremos el ejemplo anterior para recorrer diferentes partes de esta sección.

Por definición, un socket es un punto final de un enlace de comunicación bidireccional entre dos programas que se ejecutan en diferentes computadoras en una red. Un socket está vinculado a un número de puerto para que la capa de transporte pueda identificar la aplicación a la que están destinados los datos.

4.1. El servidor

Por lo general, un servidor se ejecuta en una computadora específica en la red y tiene un socket que está vinculado a un número de puerto específico. En nuestro caso, usamos la misma computadora que el cliente e iniciamos el servidor en el puerto 6666 :

ServerSocket serverSocket = new ServerSocket(6666);

El servidor simplemente espera, escuchando el socket para que un cliente haga una solicitud de conexión. Esto sucede en el siguiente paso:

Socket clientSocket = serverSocket.accept();

Cuando el código del servidor encuentra el método de aceptación , se bloquea hasta que un cliente realiza una solicitud de conexión.

Si todo va bien, el servidor acepta la conexión. Tras la aceptación, el servidor obtiene un nuevo socket, clientSocket , vinculado al mismo puerto local, 6666 , y también tiene su punto final remoto configurado en la dirección y el puerto del cliente.

En este punto, el nuevo objeto Socket pone el servidor en conexión directa con el cliente, luego podemos acceder a los flujos de salida y entrada para escribir y recibir mensajes hacia y desde el cliente respectivamente:

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

De aquí en adelante, el servidor es capaz de intercambiar mensajes con el cliente sin cesar hasta que el socket se cierra con sus flujos.

Sin embargo, en nuestro ejemplo, el servidor solo puede enviar una respuesta de saludo antes de cerrar la conexión, esto significa que si ejecutamos nuestra prueba nuevamente, la conexión sería rechazada.

Para permitir la continuidad en la comunicación, vamos a tener que leer desde el flujo de entrada dentro de un tiempo bucle y única salida cuando el cliente envía una petición de terminación, vamos a ver esto en acción en el siguiente apartado.

Para cada nuevo cliente, el servidor necesita un nuevo socket devuelto por la llamada de aceptación . El serverSocket se utiliza para seguir escuchando las solicitudes de conexión mientras atiende las necesidades de los clientes conectados. No hemos permitido esto todavía en nuestro primer ejemplo.

4.2. El cliente

El cliente debe conocer el nombre de host o IP de la máquina en la que se ejecuta el servidor y el número de puerto en el que escucha el servidor.

Para realizar una solicitud de conexión, el cliente intenta encontrarse con el servidor en la máquina y el puerto del servidor:

Socket clientSocket = new Socket("127.0.0.1", 6666);

El cliente también necesita identificarse ante el servidor para que se vincule a un número de puerto local, asignado por el sistema, que utilizará durante esta conexión. No nos ocupamos de esto nosotros mismos.

The above constructor only creates a new socket when the server has accepted the connection, otherwise, we will get a connection refused exception. When successfully created we can then obtain input and output streams from it to communicate with the server:

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

The input stream of the client is connected to the output stream of the server, just like the input stream of the server is connected to the output stream of the client.

5. Continuous Communication

Our current server blocks until a client connects to it and then blocks again to listen to a message from the client, after the single message, it closes the connection because we have not dealt with continuity.

So it is only helpful in ping requests, but imagine we would like to implement a chat server, continuous back and forth communication between server and client would definitely be required.

We will have to create a while loop to continuously observe the input stream of the server for incoming messages.

Let's create a new server called EchoServer.java whose sole purpose is to echo back whatever messages it receives from clients:

public class EchoServer { public void start(int port) { serverSocket = new ServerSocket(port); clientSocket = serverSocket.accept(); out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { if (".".equals(inputLine)) { out.println("good bye"); break; } out.println(inputLine); } }

Notice that we have added a termination condition where the while loop exits when we receive a period character.

We will start EchoServer using the main method just as we did for the GreetServer. This time, we start it on another port such as 4444 to avoid confusion.

The EchoClient is similar to GreetClient, so we can duplicate the code. We are separating them for clarity.

In a different test class, we shall create a test to show that multiple requests to the EchoServer will be served without the server closing the socket. This is true as long as we are sending requests from the same client.

Dealing with multiple clients is a different case, which we shall see in a subsequent section.

Let's create a setup method to initiate a connection with the server:

@Before public void setup() { client = new EchoClient(); client.startConnection("127.0.0.1", 4444); }

We will equally create a tearDown method to release all our resources, this is best practice for every case where we use network resources:

@After public void tearDown() { client.stopConnection(); }

Let's then test our echo server with a few requests:

@Test public void givenClient_whenServerEchosMessage_thenCorrect() { String resp1 = client.sendMessage("hello"); String resp2 = client.sendMessage("world"); String resp3 = client.sendMessage("!"); String resp4 = client.sendMessage("."); assertEquals("hello", resp1); assertEquals("world", resp2); assertEquals("!", resp3); assertEquals("good bye", resp4); }

This is an improvement over the initial example, where we would only communicate once before the server closed our connection; now we send a termination signal to tell the server when we're done with the session.

6. Server With Multiple Clients

Much as the previous example was an improvement over the first one, it is still not that great a solution. A server must have the capacity to service many clients and many requests simultaneously.

Handling multiple clients is what we are going to cover in this section.

Another feature we will see here is that the same client could disconnect and reconnect again, without getting a connection refused exception or a connection reset on the server. Previously we were not able to do this.

This means that our server is going to be more robust and resilient across multiple requests from multiple clients.

How we will do this is to create a new socket for every new client and service that client's requests on a different thread. The number of clients being served simultaneously will equal the number of threads running.

The main thread will be running a while loop as it listens for new connections.

Enough talk, let's create another server called EchoMultiServer.java. Inside it, we will create a handler thread class to manage each client's communications on its socket:

public class EchoMultiServer { private ServerSocket serverSocket; public void start(int port) { serverSocket = new ServerSocket(port); while (true) new EchoClientHandler(serverSocket.accept()).start(); } public void stop() { serverSocket.close(); } private static class EchoClientHandler extends Thread { private Socket clientSocket; private PrintWriter out; private BufferedReader in; public EchoClientHandler(Socket socket) { this.clientSocket = socket; } public void run() { out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { if (".".equals(inputLine)) { out.println("bye"); break; } out.println(inputLine); } in.close(); out.close(); clientSocket.close(); } }

Notice that we now call accept inside a while loop. Every time the while loop is executed, it blocks on the accept call until a new client connects, then the handler thread, EchoClientHandler, is created for this client.

What happens inside the thread is what we previously did in the EchoServer where we handled only a single client. So the EchoMultiServer delegates this work to EchoClientHandler so that it can keep listening for more clients in the while loop.

Seguiremos usando EchoClient para probar el servidor, esta vez crearemos múltiples clientes, cada uno enviando y recibiendo múltiples mensajes del servidor.

Iniciemos nuestro servidor usando su método principal en el puerto 5555 .

Para mayor claridad, todavía pondremos pruebas en una nueva suite:

@Test public void givenClient1_whenServerResponds_thenCorrect() { EchoClient client1 = new EchoClient(); client1.startConnection("127.0.0.1", 5555); String msg1 = client1.sendMessage("hello"); String msg2 = client1.sendMessage("world"); String terminate = client1.sendMessage("."); assertEquals(msg1, "hello"); assertEquals(msg2, "world"); assertEquals(terminate, "bye"); } @Test public void givenClient2_whenServerResponds_thenCorrect() { EchoClient client2 = new EchoClient(); client2.startConnection("127.0.0.1", 5555); String msg1 = client2.sendMessage("hello"); String msg2 = client2.sendMessage("world"); String terminate = client2.sendMessage("."); assertEquals(msg1, "hello"); assertEquals(msg2, "world"); assertEquals(terminate, "bye"); }

Podríamos crear tantos de estos casos de prueba como queramos, cada uno generando un nuevo cliente y el servidor los servirá a todos.

7. Conclusión

En este tutorial, nos hemos centrado en una introducción a la programación de sockets sobre TCP / IP y escribimos una aplicación cliente / servidor simple en Java.

El código fuente completo del artículo se puede encontrar, como de costumbre, en el proyecto GitHub.