Ejercicio Sockets en Java

En este tutorial muestro cómo funciona los Sockets en Java para ello vamos a crear 2 clases ejecutables MainCliente  y MainServidor y dos clases objeto que son Cliente y servidor; Empecemos con los objetos:

CLIENTE.JAVA

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

/**
 *
 * @author usuario
 */
public class Cliente {

    Socket cliente2;

    public Cliente() throws IOException {
        
    }

    
    

    public void inicio() {
        try {
            this.cliente2 = new Socket(«127.0.0.1», 40000);
             DataOutputStream out = new DataOutputStream(cliente2.getOutputStream());

            DataInputStream input = new DataInputStream(cliente2.getInputStream());
            String str = «»;
            String salida=»»;
            Scanner sca =new Scanner(System.in);
            
            System.out.println(«aqui llego»);            
            System.out.println(«Di algo y se añadi pondrá en mayúsculas»);
            str=sca.next();
            out.writeUTF(str);
            
            salida=input.readUTF();
            
            System.out.println(salida);
            
        } catch (Exception ex) {
            System.out.println(«error «+ex.getMessage());
        }
    }
}

SERVIDOR.JAVA

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author usuario
 */
public class Servidor {

    ServerSocket server;
    Socket cliente;

    public void servidor()  {

    }

    public void inicializar() throws IOException {
        try {
            
            this.server = new ServerSocket(40000);
            this.cliente = new Socket();
            this.cliente = this.server.accept();
            DataOutputStream out = new DataOutputStream(this.cliente.getOutputStream());

            DataInputStream input = new DataInputStream(this.cliente.getInputStream());
            String str = «»;
            while (true) {
                System.out.println(«Servidor iniciado»);
                str = input.readUTF();
                str = str.toUpperCase();
                out.writeUTF(str);

            }
        } catch (Exception ex) {

        }
    }
}

Creamos las dos clases ejecutables Main:

MAINCLIENTE.JAVA:

import java.io.IOException;

/**
 *
 * @author usuario
 */
public class MainCliente {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
        Cliente cli =new Cliente();
        cli.inicio();
    }
    
}

MAINSERVIDOR.JAVA

import java.io.IOException;

/**
 *
 * @author usuario
 */
public class MainServidor {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
      
            
            Servidor server =new Servidor();
            server.inicializar();
            
            
      
        
    }
    
}

Existe otra manera de hacerlo y es con BufferedReader aquí dejo el tutorial:

CONTENIDO OCULTO

OTRO TIPO DE CONTENIDO

CONTENIDO OCULTO

OTRO TIPO DE CONTENIDO

Esto ha sido todo por el tutorial de hoy espero que hayan aprendido algo y hasta la próxima.

Deja un comentario

Información básica sobre protección de datos Ver más

  • Responsable: Tomas Gonzalez.
  • Finalidad:  Moderar los comentarios.
  • Legitimación:  Por consentimiento del interesado.
  • Destinatarios y encargados de tratamiento:  No se ceden o comunican datos a terceros para prestar este servicio.
  • Derechos: Acceder, rectificar y suprimir los datos.
  • Información Adicional: Puede consultar la información detallada en la Política de Privacidad.

error: Content is protected !!

Descubre más desde InfoGonzalez - Blog de formador e informático

Suscríbete ahora para seguir leyendo y obtener acceso al archivo completo.

Seguir leyendo

Este sitio web utiliza cookies, si necesitas más información puedes visitar nuestra política de privacidad    Ver
Privacidad
Creative Commons License
Except where otherwise noted, the content on this site is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.