analytics

Mostrando entradas con la etiqueta tcp-ip. Mostrar todas las entradas
Mostrando entradas con la etiqueta tcp-ip. Mostrar todas las entradas

lunes, 2 de enero de 2017

Servidor de sockets TCP-IP


Servidor de Sockets TCP-IP



Ahora vamos a ver como crear un servidor de sockets por tcp-ip, es decir, una pequeña aplicación que estará permanentemente "escuchando" en un puerto a la espera de conexiones entrantes por dicho puerto. Cuando llegue una petición, crearemos un hilo con un nuevo cliente que ejecutará el tratamiento correspondiente a la nueva petición.

Para empezar, vamos a ver como quedaría la clase de ServerSockets



import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.log4j.Logger;

public class SocketServer implements Runnable {
    
    private ServerSocket serverSocket;
    private boolean socketReadActive;
    private int timeOut;
    final static Logger mainLog = Logger.getLogger(SocketServer.class);

    public  SocketServer(int port, int timeOut) {
        try{
            this.socketReadActive = true;
            this.serverSocket = new ServerSocket(port);
            this.timeOut = timeOut;
        } catch (IOException ex) {
            mainLog.error("SocketServer (): IOException" ,ex);
            this.closeSocketServer();
        }
    }

    public void run() {
         
     
        while (this.socketReadActive) {
            try {
                    Socket clientSocket = this.serverSocket.accept();
                    Client client = new Client(clientSocket, this.timeOut);
                    new Thread(client).start();                    
                    mainLog.debug("Connected client: " + clientSocket.getInetAddress() + ":" + clientSocket.getPort());
            } catch (Exception ex) {
                mainLog.error("run (): Exception" ,ex);
                this.closeSocketServer();
            }
        }
    }

    public void closeSocketServer() {
        this.socketReadActive = false;
        try {
            if (this.serverSocket != null) {
                this.serverSocket.close();
                this.serverSocket = null;
            }
        }
        catch(Exception ex){
            mainLog.error("closeSocketServer (): Exception" ,ex);
        }
    }
}



Como veis, es sencillo. Un Thread que se ejecuta constantemente a la escucha de nuevas conexiones entrantes. Cuando llega una conexión entrante, instancia un cliente Client, cuyo código será



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.log4j.Logger;


public class Client implements Runnable{

 final static Logger mainLog = Logger.getLogger(Client.class);
 
 private Socket clientSocket;
 private int timeout;
 
 public Client(Socket clientSocket, int timeout){
  this.clientSocket = clientSocket;
  this.timeout = timeout;
  
 }
 
 
 @Override
 public void run() {
  
  // set timestamp al socket de cliente
  try {
   this.clientSocket.setSoTimeout(timeout);
  } catch (SocketException e) {
   mainLog.error("Client run error " , e);
  }
  
  // procesar la petición
   BufferedReader input;
  try {
   
   input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
   String trama = input.readLine();
   
   
   try{
    
    // AQUI vendría el código de tratamiento de la petición

   } catch (Exception e){    
    mainLog.error("Client run error conectando a BD " , e);
   }
   
   
  } catch (Exception e) {      
   mainLog.error("Client run error abriendo socket ",e);
  }
          

 }


}

Sencillo cliente que se ejecuta en un hilo aparte (cada nuevo cliente será un hilo distinto), lo cual permite múltiples ejecuciones de cliente paralelas. El código de tratamiento de la petición ya depende del caso concreto.