Posts tagged ‘Enviar imagen por sockets java’

julio 27, 2011

Enviar imagen por sockets

Salida
===========================================================
Server started port 8081
Waiting for connections…
New connection /127.0.0.1
Image received!
Server close.

===========================================================

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import javax.imageio.ImageIO;
/**=
 * @author leyer
 */
class _Server extends ServerSocket implements Runnable{
	public _Server(int port, int backlog, InetAddress bindAddr)throws IOException {
		super(port, backlog, bindAddr);
		System.out.println("Server started port "+port);
	}
	public void start(){
		new Thread(this).start();
	}
	@Override
	public void run() {
		System.out.println("Waiting for connections...");
		try {
			Socket socket=accept();
			System.out.println("New connection "+socket.getInetAddress());
			BufferedImage bufferedImage = ImageIO.read(socket.getInputStream());
			ImageIO.write(bufferedImage,"png", new FileOutputStream("/home/leyer/image.png"));
			System.out.println("Image received!");	
			socket.close();
			close();
			System.out.println("Server close.");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
public class Transfer {
	public static void main(String args[]){
		try {
			new _Server(8081, 1, InetAddress.getByName("127.0.0.1")).start();
			Socket socket=new Socket( InetAddress.getByName("127.0.0.1"),8081);
			BufferedImage bufferedImage = ImageIO.read(new File("/home/leyer/lsm.png"));
			ImageIO.write(bufferedImage, "png", socket.getOutputStream());
			socket.getOutputStream().flush();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}