How to send Image over IP Socket in Java?
I'm trying to send an Image object over a IP Socket, I've got everything work except I don't know how to get Image byte size to control transfer of bytes over Socket?
Also, is there a tutorial on sending Image objects over IP Socket connections?
Thank,
Jon
[293 byte] By [
Joncamp] at [2007-11-11 9:53:07]

# 1 Re: How to send Image over IP Socket in Java?
Hi some months ago i wrote this server-client to send images. First run the server and then the client. select an image. and then it will be sent over a socket and it will be displayed in the client side. You can send objects using the ObjectOutStream class.
Here is the code for server and client.
Server:
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Server extends JFrame {
ServerSocket ser;
Socket con;
ObjectOutputStream salida;
ObjectInputStream entrada;
public Server() {
}
void ejecutar(){
try{
ser = new ServerSocket( 5700,1 );
con = ser.accept();
salida = new ObjectOutputStream(con.getOutputStream());
salida.flush();
entrada = new ObjectInputStream(con.getInputStream());
procesar();
}
catch(IOException e){}
}
void procesar(){
while(true){
try{
JFileChooser fc=new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
int r = fc.showOpenDialog(this);
File f = fc.getSelectedFile();
salida.writeObject( new ImageIcon(""+f) );
}catch(IOException e){}
}
}
public static void main(String args[]) {
Server srv = new Server();
srv.ejecutar();
}
}
Client:
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Cliente extends JFrame {
JTextField tf;
Lienzo lienzo;
Socket con;
ObjectOutputStream salida;
ObjectInputStream entrada;
public Cliente(){
super("Cliente");
Container c = getContentPane();
tf = new JTextField(10);
lienzo=new Lienzo();
c.add(lienzo);
pack();
setSize(100,100);
setVisible(true);
}
void ejecutar(){
try{
con = new Socket("127.0.0.1",5700);
salida = new ObjectOutputStream(con.getOutputStream());
salida.flush();
entrada = new ObjectInputStream(con.getInputStream());
procesar();
}
catch(IOException e){}
}
void procesar() throws IOException {
try{
while(true){
ImageIcon img = (ImageIcon) entrada.readObject();
escribir(img);
}
}catch(ClassNotFoundException e){}
}
void escribir(final ImageIcon img){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
lienzo.pinta(img);
}
}
);
}
public static void main( String args[] ){
Cliente cl = new Cliente();
cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cl.ejecutar();
}
class Lienzo extends JPanel{
ImageIcon img=null ;
public Lienzo(){
}
public void pinta(ImageIcon img){
this.img=img;
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if(img!=null)
img.paintIcon(this,g,10,10);
}
}
}
Thats all.
virux at 2007-11-11 22:32:15 >
