Ah @Ruusa se le habla un par de veces sobre el GeSHI
![](https://3.bp.blogspot.com/-O6qDroNEzts/W8sWHPnV3MI/AAAAAAAADJw/mypp_PTYxbA_uKr7E-O-x0epDjSUdk3mwCK4BGAYYCw/s1600/geshi.gif)
Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.
Mostrar Mensajes MenúCita de: JordyVP en 8 Marzo 2021, 13:57 PM
hola comunidad programadora soy nuevo en este sitio ,mi nombre es Jordy mucho gusto, estoy aquí para aprender mas a cerca sobre el lenguaje java tengo un problema con un ejercicio y ya le e dado mil vueltas y no logro realizarlo, este ejercicio me pide que tengo q conectarme a un servidor en donde el cliente hace una petición y solo el servidor responderá con números octales (0,1,2,3,4,5,6,7),pero la conexión debe de ser solo comunicación UDP como puedo realizar eso en el siguiente código? necesito ayuda :'(/código del servidor
/*COMUNICACION UDP (protocolo sin conexión/IP) CLIENTE-SERVIDOR CON HILOS
La conexión UDP no es orientada a conexión, es decir, el servidor en principio
no sabe de donde viene el mensaje, aunque lo puede saber mirando el datagrama que le llega.
En otras palabras y comparando con la conexión TCP, UDP no necesita saber quien se conecta a él.
En UDP se envían datagramas a modo de mensajes.*/
package sockets4_servidor;
import java.io.*;
import java.net.*;
public class Sockets4_servidor {
static formu1 formu = new formu1();
static Sockets4_servidor meto = new Sockets4_servidor();
int PUERTO = 5000; //Puerto servidor
String mensa1;
byte[] buffer = new byte[1024]; //buffer donde se almacenara los mensajes
DatagramSocket socketUDP;
DatagramPacket respuesta;
InetAddress direccion;
int puertoCliente;
public static void main(String[] args) {
formu.setVisible(true);meto.conexion();meto.ejecutarconexion();}
public void ejecutarconexion() {
Thread hilo = new Thread(new Runnable() {
@Override
@SuppressWarnings("empty-statement")
public void run() {
while (true) {
try {mensaje();}
finally {;} } } } );
hilo.start();}
public void conexion() {
try {
formu1.jTextArea1.append("Esperando conexión entrante en el puerto: " + PUERTO+ "\n");
direccion = InetAddress.getLocalHost();
formu1.jTextArea1.append("Servidor IP: " + direccion + "\n");}
catch (IOException e) {System.err.println("Error "+e);} }
public void mensaje() {
try {
//Creacion del socket
socketUDP = new DatagramSocket(PUERTO);
//Preparo la respuesta
DatagramPacket peticion = new DatagramPacket(buffer, buffer.length);
//Recibo el datagrama
socketUDP.receive(peticion);
//Convierto lo recibido y mostrar el mensaje
mensa1 =new String(peticion.getData());
formu1.jTextArea1.append(mensa1+"\n");
//Obtengo el puerto y la direccion de origen
//Sino se quiere responder, no es necesario
puertoCliente = peticion.getPort();
direccion = peticion.getAddress();
mensa1="SERVIDOR: Hola Cliente";
buffer = mensa1.getBytes();
//creo el datagrama
respuesta = new DatagramPacket(buffer, buffer.length, direccion, puertoCliente);
//Envio la información
socketUDP.send(respuesta); }
catch (IOException e) {System.err.println("Error "+e);} }
}/code]
Cita de: Machacador en 6 Marzo 2021, 23:42 PM
Y sirven para descargas de varios gigas y reiniciarlas si por algún motivo se interrumpen???...
Saludos.
![]()
![]()
Cita de: Juan Pelaez en 23 Febrero 2021, 09:19 AM
Ok, Gracias a los dos ( rub'n, K-YreX ).Lo he entendido perfectamente, como parece interesante el poder seguir posibles Errores voy a intentar incorporarlo en el proyecto. También es una forma de ir aprendiendo más.
Gracias,
Ya os contaré.
@Data
public class Hola {
private String hola = "Hi!";
}
new Hola().setHola("");
new Hola().getHola();
package com.signwithmouse;
import lombok.extern.slf4j.Slf4j;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
/**
* https://foro.elhacker.net/java/problemas_con_app_simple_para_dibujar_firma_y_guardarla_como_imagen-t427969.0.html
*
* Nombre de clase = recogeFirma
* Descripcion = Clase encargada de capturar la firma que se dibuja en pantalla
*
* @version 1.0
* @author rubn
* @author google
* @author mas personas
*/
@Slf4j
public class MainJFrame extends JFrame {
private static final String TITLE = "App Firma";
private JButton jButtonBorrar = new JButton("Borrar");
private JButton jButtonGuardar = new JButton("Guardar");
private JLabel jLabelIL = new JLabel("Introduzca su firma");
private final JPanel mainJPanel = new JPanel();
//Algo de Magia
private JPanelForSign jPanelForSign = new JPanelForSign();
public MainJFrame() {
this.configureJFrame();
this.configureJPanels();
this.initBehaviour();
}
private void configureJFrame() {
super.setResizable(false);
super.setPreferredSize(new Dimension(400,350));
super.add(mainJPanel);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.pack();
super.setLocationRelativeTo(null);
super.setVisible(true);
}
private void configureJPanels() {
final TitledBorder border = new TitledBorder(TITLE);
border.setTitleJustification(TitledBorder.CENTER);
border.setTitlePosition(TitledBorder.TOP);
this.mainJPanel.setBorder(border);
this.mainJPanel.setLayout(new BorderLayout());
final JPanel panelFooter = new JPanel();
panelFooter.setLayout(new FlowLayout());
panelFooter.add(new JLabel());
panelFooter.add(jLabelIL);
panelFooter.add(jButtonBorrar);
panelFooter.add(jButtonGuardar);
mainJPanel.add(jPanelForSign);
mainJPanel.add(panelFooter,BorderLayout.SOUTH);
mainJPanel.setPreferredSize(new Dimension(450, 250));
}
private void initBehaviour() {
jButtonBorrar.addActionListener(e -> {
//Blanquear la imagen de la firma
jPanelForSign.clearSignZone();
});
jButtonGuardar.addActionListener(e -> {
jPanelForSign.guardarFirma();
});
}
public static void main(String... blabla) {
final String osType = System.getProperty("os.name");
try {
if(osType.contains("Win")) {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}else if(osType.contains("Linux")) {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
}
}catch(Exception ex) {}
new Thread(MainJFrame::new).start();
}
}
package com.signwithmouse;
import com.signwithmouse.util.GetFileChooser;
import lombok.extern.slf4j.Slf4j;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Path;
import java.util.concurrent.atomic.AtomicInteger;
/**
* JPanel donde se firmara
*/
@Slf4j
public class JPanelForSign extends JPanel {
private static final int WIDTH = 400;
private BufferedImage bufferedImage = new BufferedImage(WIDTH, WIDTH, BufferedImage.TYPE_INT_ARGB);
private final AtomicInteger uX = new AtomicInteger();
private final AtomicInteger uY = new AtomicInteger();
public JPanelForSign() {
super.setBackground(Color.WHITE);
super.requestFocus();
super.setBorder(BorderFactory.createEtchedBorder());
this.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
uX.set(e.getX());
uY.set(e.getY());
repaint();
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
final int x = e.getX();
final int y = e.getY();
final Graphics2D g2 = (Graphics2D) bufferedImage.getGraphics();
g2.setBackground(Color.WHITE);
g2.setColor(Color.BLACK);
g2.drawLine(uX.get(), uY.get(), x, y);
uX.set(x);
uY.set(y);
g2.dispose();
}
});
}
public void clearSignZone() {
this.createEmptyImage();
super.repaint();
}
private void createEmptyImage() {
bufferedImage = new BufferedImage(super.getWidth(), super.getHeight(), BufferedImage.TYPE_INT_ARGB);
final Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();
g2d.setColor(Color.BLACK);
}
@Override
public void paint(Graphics g) {
super.paint(g);
final Graphics2D graphics2D = (Graphics2D) g.create();
graphics2D.drawImage(bufferedImage, 0, 0, null);
super.repaint();
}
/**
* Método que guarda la imagen generada
*/
public void guardarFirma() {
final JFileChooser jFileChooser = GetFileChooser.getFileChooser(JFileChooser.DIRECTORIES_ONLY);
if (jFileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
Path path1 = jFileChooser.getSelectedFile().toPath();
final String fileN = path1.getFileName().toString();
if(!fileN.endsWith(".png")) {//En caso de que no termine en .png se lo concatenamos
try {
String fileName = path1.getFileName().toString().concat(".png");
path1 = path1.resolveSibling(fileName);
ImageIO.write(bufferedImage, "png", path1.toFile());
JOptionPane.showMessageDialog(null, "Imagen creada correctamente!");
} catch (IOException e) {
log.warn(e.getMessage());
JOptionPane.showMessageDialog(null, "Error al guardar!");
}
} else {
try {
final Path path2 = jFileChooser.getSelectedFile().toPath();
ImageIO.write(bufferedImage, "png", path2.toFile());
JOptionPane.showMessageDialog(null, "Imagen creada correctamente!");
} catch (IOException e) {
log.warn(e.getMessage());
JOptionPane.showMessageDialog(null, "Error al guardar!");
}
}
}
}
}