我在通过 Socket(客户端-服务器)发送图像时遇到一个小问题,我只收到“UTF”文本而不是图像对象,代码有问题吗?
此代码仅发送 UTF txt 并在服务器端接收,我使用 UTF 文本在服务器端识别图像(名称),识别后它可以将图像对象发送到客户端
/*
* ServerSide
*
*/
package Interface_class;
import configuraciones.procesador;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import javax.imageio.ImageIO;
/**
*
* @author TheCoder
*/
public class img_monitor extends Thread{
ServerSocket serverSocket;
Socket server;
BufferedImage bimg;
byte[] bytes;
public img_monitor()
{
try{
//Opening server socket
serverSocket = new ServerSocket(6066);
System.out.println("Conectado al Socket!");
}
catch(IOException ex){
System.out.println("Error en: "+ex);
}
}
public void run()
{
//This class gets the path from a property file (works well)
procesador obj = new procesador();
obj.UBARCHIVO_CONFIG();
while(true)
{
try
{
server = serverSocket.accept();
System.out.println("Nuevo cliente conectado!");
DataInputStream din=new DataInputStream(server.getInputStream());
DataOutputStream dout=new DataOutputStream(server.getOutputStream());
//Receiving image "name" from client as txt
String nombre = din.readUTF();
System.out.println(nombre);
//Using path+name of image to identify and send over socket
bimg = ImageIO.read(new File(obj.getRuta_arch_img()+nombre));
System.out.println(obj.getRuta_arch_img()+nombre);
ImageIO.write(bimg,"JPG",dout);
System.out.println("Image sent!!!");
// server.close();
//lblimg.setIcon(img);
}
catch(IOException e)
{
e.printStackTrace();
break;
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
}
客户端
/*
* Client Side
*
*/
package Interface_class;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import javax.imageio.ImageIO;
/**
*
* @author TheCoder
*/
public class Obtener_imagen extends Thread {
public Obtener_imagen() {
System.out.println("Loading Socket!");
}
public void run() {
//The class below gets info from database
CLIENTINFO_CLASS obj = new CLIENTINFO_CLASS();
obj.consulta();
try {
Socket socket = new Socket("localhost", 6066);
// DataInputStream din = new DataInputStream(socket.getInputStream());
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
//Using this to send image "name" to server, so it can identify and send image to client
dout.writeUTF(obj.getImg_name());
BufferedImage img = ImageIO.read(ImageIO.createImageInputStream(socket.getInputStream()));
System.out.println("Image received!!!!");
// socket.close();
} catch (IOException ex) {
System.out.println("Error al abrir el socket" + ex);
}
}
}