Advertisement
Guest User

Java.IO

a guest
Mar 11th, 2013
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 3.49 KB | None | 0 0
  1. import java.io.*;
  2. import java.net.*;
  3. import java.util.logging.*;
  4.  
  5. public class TCPServidor extends Thread {
  6.    
  7.    private ObjectOutputStream salida;
  8.    private ObjectInputStream entrada;
  9.    private ServerSocket servidor;
  10.    private Socket conexion;
  11.    int Port = 6789;
  12.    
  13.     public TCPServidor()
  14.     {
  15.     }
  16.    
  17.     public void setServidor() throws IOException
  18.     {
  19.            // configurar servidor para que reciba conexiones; procesar las conexiones
  20.       try {
  21.  
  22.          // Paso 1: crear un objeto ServerSocket.
  23.          servidor = new ServerSocket(Port);
  24.  
  25.          while ( true ) {
  26.  
  27.             try {
  28.                waitConexion(); // Paso 2: esperar una conexión.
  29.                flujosES();        // Paso 3: obtener flujos de entrada y salida.
  30.                getConexion(); // Paso 4: procesar la conexión.
  31.             }
  32.  
  33.             // procesar excepción IOXException cuando el cliente cierre la conexión
  34.             catch ( IOException e ) {
  35.                System.err.println( "El servidor terminó la conexión" );
  36.             }
  37.  
  38.             finally {
  39.                logout();   // Paso 5: cerrar la conexión.
  40.             }
  41.  
  42.          } // fin de instrucción while
  43.  
  44.       } // fin del bloque try
  45.  
  46.       // procesar problemas con E/S
  47.       catch ( IOException e ) {
  48.          printMensaje( "\n Problemas con los flujos" );
  49.       }
  50.  
  51.     }
  52.    
  53.     private void waitConexion()
  54.     {
  55.         printMensaje( "Esperando una conexión\n" );
  56.         conexion = servidor.accept(); // permitir al servidor aceptar la conexión  
  57.         printMensaje( "Conexión recibida de: " + conexion.getInetAddress().getHostName() );
  58.     }
  59.    
  60.     private void getConexion() throws IOException
  61.     {
  62.         // enviar mensaje de conexión exitosa al cliente
  63.       String mensaje = "Conexión establecida";
  64.       sentMensaje( mensaje );
  65.  
  66.       do { // procesar los mensajes enviados por el cliente
  67.  
  68.          // leer el mensaje y mostrarlo en pantalla
  69.          try {
  70.             mensaje = ( String ) entrada.readUTF();
  71.             printMensaje( "\n" + mensaje );
  72.          }
  73.  
  74.          // atrapar problemas que pueden ocurrir al tratar de leer del cliente
  75.          catch ( IOException e ) {
  76.             printMensaje( "\nError al enviar" );
  77.         }
  78.  
  79.       } while ( !mensaje.equals( "CLIENTE>>> TERMINAR" ) );
  80.    
  81.     }
  82.    
  83.     private void sentMensaje(String msj) throws IOException
  84.     {
  85.         // enviar objeto al cliente
  86.       try {
  87.          salida.writeObject( "SERVIDOR>>> " + msj );
  88.          salida.flush();
  89.          printMensaje( "\nSERVIDOR>>> " + msj );
  90.       }
  91.  
  92.       // procesar problemas que pueden ocurrir al enviar el mensaje
  93.       catch ( IOException e ) {
  94.          printMensaje( "\nError al enviar" );
  95.       }
  96.     }
  97.  
  98.     private void printMensaje(final String msj)
  99.     {
  100.         System.out.println(msj);
  101.     }
  102.    
  103.     private void logout() throws IOException
  104.     {
  105.         System.out.println("El usuario llamado" + conexion.getInetAddress().getHostName() + " se ha desconectado.");
  106.        
  107.         try{
  108.             conexion.close();
  109.             salida.close();
  110.             entrada.close();
  111.         }
  112.         catch (IOException e) {
  113.             Logger.getLogger(TCPServidor.class.getName()).log(Level.SEVERE, null, e);
  114.         }
  115.     }
  116.  
  117.     private void flujosES()
  118.     {
  119.       salida = new ObjectOutputStream( conexion.getOutputStream() );
  120.       salida.flush();
  121.       entrada = new ObjectInputStream( conexion.getInputStream() );
  122.       printMensaje( "\nSe recibieron los flujos de E/S\n" );
  123.     }
  124.  
  125.  
  126.     public static void main(String args[]) throws IOException
  127.     {
  128.         TCPServidor chat=new TCPServidor();
  129.         chat.setServidor();
  130.     }
  131.    
  132. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement