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.

Gracias por visitar mi blog de informática, mi nombre es Tomás y soy formador y desarrollador web. Si quiere usted dejarme alguna sugerencia, ayuda o quiere un servicio de formación estoy escuchando ofertas en tomas.gonzalez@infogonzalez.com, en Facebook a https://www.facebook.com/Infogonzalez estoy deseando escucharle. Su duda o sugerencia NO molesta.

Tomas Gonzalez
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.
A %d blogueros les gusta esto: