Solved

sending images through sockets

Posted on 2003-11-15
19
477 Views
Last Modified: 2010-03-31
i have a client/ server application
and i want to send an image from the server and recieve it on the other side
i read alot about converting the image into bytes and send it but i dont know how to do it
or getting each pixel of the picture and send it  which have no idea about either
can any body help me please
0
Comment
Question by:omash
  • 9
  • 6
  • 4
19 Comments
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
If you have the image as a file, simply send it over using a BufferedOutputStream and read it using a BufferedInputStream
0
 
LVL 1

Expert Comment

by:omashhour
Comment Utility
how is that possible
i dont have to convert the image into bytes and on the client side convert it from bytes to image again ??
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
You have two options:

a. file to file
b. memory to memory

or a combination of the two. What do you actually want to do in detail?
0
 
LVL 1

Expert Comment

by:omashhour
Comment Utility
file to file
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 70 total points
Comment Utility
           public boolean sendFile(String fileName) {
                  FileInputStream from = null;
                  try {
                        int bytesRead = 0;
                        from = new FileInputStream(fileName);
                        out = new BufferedOutputStream(socket.getOutputStream());
                        byte[] buffer = new byte[BUF_SIZE];
                        while((bytesRead = from.read(buffer)) != -1) // Read bytes until EOF
                              out.write(buffer, 0, bytesRead);                                    //       write bytes
                  }
                  // Always close the streams, even if exceptions were thrown
                  catch (IOException e) {
                        return false;
                  }
                  finally {
                        if (from != null) try { from.close(); } catch (IOException e) { ; }
                        if (out != null) try { out.close(); } catch (IOException e) { ; }
                        if (socket != null) try { socket.close(); } catch (IOException e) { ; }
                  }
                  return true;
            }
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
That code can be easily adapted to read the incoming file.

>>from = new FileInputStream(fileName);

would be changed to a BufferedInputStream opened on the receiving socket

>>out = new BufferedOutputStream(socket.getOutputStream());

the output stream above can be changed to a file output stream
0
 
LVL 1

Expert Comment

by:omashhour
Comment Utility
can i have more than 1 outputstream on the server

because i already have printwriter will that be a problem ??
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
You should send the 'bursts' of conversation separately. If you want to send text with the PrintWriter (you can't send binary data with it), open the output stream on the socket, send it and close it. Then send the image in the same way with BufferedOutputStream.
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>You should send the 'bursts' of conversation separately

But you can keep the socket open (the above code closes it)
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

Author Comment

by:omash
Comment Utility
im having an error in bufferedoutputstreampart
0
 

Author Comment

by:omash
Comment Utility
do u want me to send u the code?
0
 

Author Comment

by:omash
Comment Utility
this is the server side

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.net.*;

class Server extends JFrame implements ActionListener
{
    JButton send=new JButton("Send");
    JButton sendpic=new JButton("Send Pic");
    JLabel beyekteb=new JLabel(" ");
    JTextArea itext=new JTextArea(4, 20);
    JTextArea dtext=new JTextArea(15, 20);
    Nick nickName=null;
    About about1=new About();
    Help help1=new Help();
    JMenuBar bar=new JMenuBar();
    JMenu file=new JMenu("File");
    JMenu help=new JMenu("Help");
    JMenuItem nick=new JMenuItem("Change Nick");
    JMenuItem about=new JMenuItem("About");
    JMenuItem hhelp=new JMenuItem("Help");
    ServerSocket server=null;
    Socket incoming=null;
    PrintWriter out=null;
    BufferedReader in=null;
    String line1;
    String n;
    Date now=new Date();
    JScrollPane scroll= new JScrollPane(dtext);
   
   
    Server()
    {
        super("Server");
        bar.add(file);
        bar.add(help);
        file.add(nick);
        help.add(hhelp);
        help.add(about);
        dtext.setEditable(false);
        send.addActionListener(this);
        sendpic.addActionListener(this);
        nick.addActionListener(this);
        about.addActionListener(this);
        hhelp.addActionListener(this);
        itext.setBorder(BorderFactory.createEtchedBorder());
        dtext.setBorder(BorderFactory.createEtchedBorder());
        BorderLayout bord=new BorderLayout();
        BorderLayout bord1=new BorderLayout();
        BorderLayout bord2=new BorderLayout();
        JPanel pane2=new JPanel();
        pane2.setLayout(bord);
        pane2.add(itext);
        pane2.add("East", send);
        pane2.add("West",sendpic);
        JPanel pane1=new JPanel();
        pane1.setLayout(bord1);
        pane1.add("North",scroll);
        pane1.add(pane2);
        pane1.add("South", beyekteb);
        JPanel pane=new JPanel();
        pane.setLayout(bord2);
        pane.add("North", bar);
        pane.add(pane1);
        setContentPane(pane);
        pack();
        show();
    }
          public void setNick(String n)
     {
         this.n=n;
     }
        public void listenSocket()
        {
            try
            {
                server=new ServerSocket(1348);
                incoming=server.accept();
           
                in=new BufferedReader(new InputStreamReader(incoming.getInputStream()));
                out=new PrintWriter(incoming.getOutputStream(), true);
               
               
               
              for(int i=0;i<5000;i++)
               {
                   line1=in.readLine();
                   dtext.append("\n"+line1);
               }    
               
           
            }
            catch(Exception e)
            {
            }
           
   
        }
       public boolean sendFile() {
               
               FileInputStream from = null;
               BufferedOutputStream out2=null;
               try {
                    int bytesRead = 0;
                    from = new FileInputStream("I:\\Image Transfer\\Me\\DSC00468");
                    out2 = new BufferedOutputStream(incoming.getOutputStream());
                    byte[] buffer = new byte[1024];
                    while((bytesRead = from.read(buffer)) != -1)
                         out2.write(buffer, 0, bytesRead);                    
               }
               catch (IOException e) {
                    return false;
               }
        }

   
    public static void main(String [] args)
    {
        Server serve=new Server();
        serve.setTitle("Server Program");
        WindowListener l = new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                        System.exit(0);
                }
        };
        serve.addWindowListener(l);
        serve.pack();
        serve.setVisible(true);
      serve.listenSocket();
        //serve.sendFile();
    }
   
    public void actionPerformed(ActionEvent e)
    {
        Object source=e.getSource();
        if(source==nick)
        {
            if( nickName == null )
             nickName = new Nick(this) ;
            nickName.setVisible(true);
        }
        if(source==about)
        {
            about1.setVisible(true);
        }
        if(source==hhelp)
        {
            help1.setVisible(true);
        }
        if(source==send)
        {
            listenSocket();
            String input=(n+":"+itext.getText());
            out.println(input);
            dtext.append("\n"+input);
            itext.setText("");
            beyekteb.setText("Your chat started at "+now);
        }
        if(source==sendpic)
        {
           sendFile();
        }
    }
   
}

class Nick extends JFrame implements ActionListener
{
    JButton set=new JButton("Set");
    JLabel label=new JLabel("New Nick");
    JTextField text=new JTextField(10);
    String n;
    Server server;
   
    Nick(Server server)
    {
        super("Change Nick");
        this.server = server ;
        set.addActionListener(this);
        BorderLayout bord=new BorderLayout();
        FlowLayout flow=new FlowLayout();
        JPanel pane1=new JPanel();
        pane1.setLayout(flow);
        pane1.add(label);
        pane1.add(text);
        JPanel pane=new JPanel();
        pane.setLayout(bord);
        pane.add(pane1);
        pane.add("South", set);
        setContentPane(pane);
        pack();
        setVisible(false);
    }
   
   public void actionPerformed(ActionEvent e) {
        Object source=e.getSource();
        if(source==set)
        {
            n=text.getText();
            server.setNick(n);
            setVisible(false);
        }
    }
}
class About extends JFrame implements ActionListener
{
    JLabel name=new JLabel("Created by:Omar Mashhour");
    JLabel date=new JLabel("Date:12/11/2003");
    JButton close=new JButton("Close");
   
    About()
    {
        super("About");
        close.addActionListener(this);
        GridLayout grid=new GridLayout(2,1);
        BorderLayout bord=new BorderLayout();
        JPanel pane1=new JPanel();
        pane1.setLayout(grid);
        pane1.add(name);
        pane1.add(date);
        JPanel pane=new JPanel();
        pane.setLayout(bord);
        pane.add(pane1);
        pane.add("South",close);
        setContentPane(pane);
        pack();
        setVisible(false);
    }
   
    public void actionPerformed(ActionEvent e) {
        Object source=e.getSource();
        if(source==close)
        {  
            setVisible(false);
        }
    }
   
}
class Help extends JFrame implements ActionListener
{
    JLabel label=new JLabel("No help available at the moment");
    JButton close=new JButton("Close");
   
    Help()
    {
        super("Help");
        close.addActionListener(this);
        GridLayout grid=new GridLayout(2,1);
        JPanel pane=new JPanel();
        pane.setLayout(grid);
        pane.add(label);
        pane.add(close);
        setContentPane(pane);
        setVisible(false);
        pack();
    }
       
    public void actionPerformed(ActionEvent e) {
        Object source=e.getSource();
        if(source==close)
        {
            setVisible(false);
        }
    }    
       
}
       
0
 

Author Comment

by:omash
Comment Utility
and this is the client side
 i dont know if what ive done is right please check what ive done

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.net.*;

class Client extends JFrame implements ActionListener
{
    JButton send=new JButton("Send");
    JLabel beyekteb=new JLabel(" ");
    JTextArea itext=new JTextArea(4, 20);
    JTextArea dtext=new JTextArea(15, 20);
    JTextField bob=new JTextField(10);
    Nick nickName=null;
    About about1=new About();
    Help help1=new Help();
    JMenuBar bar=new JMenuBar();
    JMenu file=new JMenu("File");
    JMenu edit=new JMenu("Edit");
    JMenu help=new JMenu("Help");
    JMenuItem new1=new JMenuItem("New...");
    JMenuItem open=new JMenuItem("Open");
    JMenuItem save=new JMenuItem("Save");
    JMenuItem exit=new JMenuItem("Exit");
    JMenuItem nick=new JMenuItem("Change Nick");
    JMenuItem about=new JMenuItem("About");
    JMenuItem hhelp=new JMenuItem("Help");
    Socket socket=null;
    PrintWriter out=null;
    BufferedReader in=null;
    String line;
    String n;
    Date now = new Date();
    JScrollPane scroll= new JScrollPane(dtext);
       
   
   
    Client()
    {
        super("Client");
        bar.add(file);
        bar.add(edit);
        bar.add(help);
        file.add(new1);
        file.add(open);
        file.addSeparator();
        file.add(save);
        file.addSeparator();
        file.add(exit);
        edit.add(nick);
        help.add(hhelp);
        help.addSeparator();
        help.add(about);
        dtext.setEditable(false);
        new1.addActionListener(this);
        open.addActionListener(this);
        save.addActionListener(this);
        exit.addActionListener(this);
        send.addActionListener(this);
        nick.addActionListener(this);
        about.addActionListener(this);
        hhelp.addActionListener(this);
        itext.setBorder(BorderFactory.createEtchedBorder());
        dtext.setBorder(BorderFactory.createEtchedBorder());
        BorderLayout bord=new BorderLayout();
        BorderLayout bord1=new BorderLayout();
        BorderLayout bord2=new BorderLayout();
        JPanel pane2=new JPanel();
        pane2.setLayout(bord);
        pane2.add(itext);
        pane2.add("East", send);
        JPanel pane1=new JPanel();
        pane1.setLayout(bord1);
        pane1.add("North",scroll);
        pane1.add(pane2);
        pane1.add("South", beyekteb);
        JPanel pane=new JPanel();
        pane.setLayout(bord2);
        pane.add("North", bar);
        pane.add(pane1);
        setContentPane(pane);
    }
     
     public void listenSocket(){  
       
        try
        {
            socket=new Socket("62.193.76.85",1348);
            in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out=new PrintWriter(socket.getOutputStream(), true);
           
         
           for(int i=0;i<5000;i++)
           {  
              line=in.readLine();
              dtext.append("\n"+line);
           }
            readFile();
           
           
           
           
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
     public boolean readFile() {
               socket=new Socket("62.193.76.85",1348);
               FileOutputStream from = null;
               BufferedInputStream out2=null;
               try {
                    int bytesRead = 0;
                    from = new FileOutputStream("C:\\Documents and Settings\\Mash\\My Documents\\My Pictures\\pic.jpg");
                    out2 = new BufferedInputStream(socket.getInputStream());
                    byte[] buffer = new byte[1024];
                    while((bytesRead = out2.read(buffer)) != -1)
                         from.write(buffer, 0, bytesRead);                    
               }
               catch (IOException e) {
                    return false;
               }
   }
     
    public static void main(String [] args)
    {
        Client client=new Client();
        client.setTitle("MCP V1.0");
        WindowListener l = new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                        System.exit(0);
                }
        };

        client.addWindowListener(l);
        client.pack();
        client.setVisible(true);
      client.listenSocket();
    }
   
    public void openFile()
    {
        JFileChooser chooser=new JFileChooser();
        //chooser.setCurrentDirectory(new File("C:\\"));
        //chooser.setFileFilter(
        //new javax.swing.filechooser.FileFilter()
        //{
         //   public boolean accept(File f)
          //  {
           //     return f.getName().toLowerCase().endsWith("txt")
            //    || f.isDirectory();
            //}
            //public String getDescription()
            //{
             //   return "Text files";
            //}
        //});
        int r=chooser.showOpenDialog(this);
        File f=chooser.getSelectedFile();
        try{
        FileReader filein=new FileReader(f);
        int inbyte;
        do
        {
            inbyte=filein.read();
            if(inbyte!=-1)
            {
                String inc=Integer.toString(inbyte);
                itext.append(inc);
            }
        }while(inbyte!=-1);
        //ProgressMonitorInputStream progressin=new ProgressMonitorInputStream(this,
        //"Reading "+f.getName(), filein);
        //InputStreamReader inread =new InputStreamReader(progressin);
        //BufferedReader readin=new BufferedReader(inread);
        //String tfile=readin.readLine();
        //itext.append(tfile);
        }
        catch(IOException ex)
        {
        }
       
   
    }
     
    public void saveFile()
    {
        JFileChooser chooser=new JFileChooser();
        chooser.setCurrentDirectory(new File("C:\\"));
        chooser.setFileFilter(
        new javax.swing.filechooser.FileFilter()
        {
            public boolean accept(File f)
            {
                return f.getName().toLowerCase().endsWith("txt")
                || f.isDirectory();
            }
            public String getDescription()
            {
                return "Text files";
            }
        });
        int r=chooser.showSaveDialog(this);
        File f=chooser.getSelectedFile();
        /*try{FileInputStream filein=new FileInputStream(f);
        InputStreamReader inread =new InputStreamReader(filein);
        BufferedReader readin=new BufferedReader(inread);
        String tfile=readin.readLine();
        itext.append(tfile);
        }
        catch(IOException ex)
        {
        }*/
       
   
    }
   
    public void setNick(String n)
     {
        this.n=n;
     }
    public void send()
    {
            String input=(n+":"+itext.getText());
            out.println(input);
            dtext.append("\n"+input);
            itext.setText("");
            beyekteb.setText("Your Chat Started at "+now);
    }
    public void actionPerformed(ActionEvent e)
    {
        Object source=e.getSource();
        if(source==new1)
        {
            dtext.setText("");
            itext.setText("");
        }
        if(source==open)
        {
            openFile();
            send();
        }
        if(source==save)
        {
            saveFile();
        }
        if(source==exit)
        {
            setVisible(false);
        }
        if(source==send)
        {  
            send();/*String input=(n+":"+itext.getText());
            out.println(input);
            dtext.append("\n"+input);
            itext.setText("");
            beyekteb.setText("Your Chat Started at "+now);
             */
        }
        if(source==nick)
        {
            if( nickName == null )
             nickName = new Nick(this) ;
            nickName.setVisible(true);
        }
        if(source==about)
        {
            about1.setVisible(true);
        }
        if(source==hhelp)
        {
            help1.setVisible(true);
        }
       
       
    }
   
}

class Nick extends JFrame implements ActionListener
{
    JButton set=new JButton("Set");
    JLabel label=new JLabel("New Nick");
    JTextField text=new JTextField(10);
    String n;
    Client client;
   
    Nick(Client client)
    {
        super("Change Nick");
        this.client = client ;
        set.addActionListener(this);
        BorderLayout bord=new BorderLayout();
        FlowLayout flow=new FlowLayout();
        JPanel pane1=new JPanel();
        pane1.setLayout(flow);
        pane1.add(label);
        pane1.add(text);
        JPanel pane=new JPanel();
        pane.setLayout(bord);
        pane.add(pane1);
        pane.add("South", set);
        setContentPane(pane);
        pack();
        setVisible(false);
    }
   
   public void actionPerformed(ActionEvent e) {
        Object source=e.getSource();
        if(source==set)
        {
            n=text.getText();
            client.setNick(n);
            setVisible(false);
        }
    }
}

class About extends JFrame implements ActionListener
{
    JLabel name=new JLabel("Created by:Omar Mashhour");
    JLabel date=new JLabel("Date:12/11/2003");
    JButton close=new JButton("Close");
   
    About()
    {
        super("About");
        close.addActionListener(this);
        GridLayout grid=new GridLayout(2,1);
        BorderLayout bord=new BorderLayout();
        JPanel pane1=new JPanel();
        pane1.setLayout(grid);
        pane1.add(name);
        pane1.add(date);
        JPanel pane=new JPanel();
        pane.setLayout(bord);
        pane.add(pane1);
        pane.add("South",close);
        setContentPane(pane);
        pack();
        setVisible(false);
    }
   
    public void actionPerformed(ActionEvent e) {
        Object source=e.getSource();
        if(source==close)
        {  
            setVisible(false);
        }
    }
   
}
class Help extends JFrame implements ActionListener
{
    JLabel label=new JLabel("No help please go to HELL");
    JButton close=new JButton("Close");
   
    Help()
    {
        super("Help");
        close.addActionListener(this);
        GridLayout grid=new GridLayout(2,1);
        JPanel pane=new JPanel();
        pane.setLayout(grid);
        pane.add(label);
        pane.add(close);
        setContentPane(pane);
        setVisible(false);
        pack();
    }
       
    public void actionPerformed(ActionEvent e) {
        Object source=e.getSource();
        if(source==close)
        {
            setVisible(false);
        }
    }    
       
}
       
       


       
       


0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Please don't post so much code! What bit am I meant to be looking at?
0
 

Author Comment

by:omash
Comment Utility
sorry

the bit thats supposed to send the image in server code its called sendFile but i have a complie error her

and in the client code its called readFile
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
One thing at a time:

1. sendFile

a. pass the filename as a parameter to the function - don't hard code it
b. you must close the output stream
0
 
LVL 1

Expert Comment

by:omashhour
Comment Utility
i have to make a filechooser like this in the server
right??
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Not sure what you mean or what your question is. If you are using a file chooser component (JFileChooser) you should call that sendFile function using the chosen file name as a parameter. Don't forget that you will require a separate thread to call sendFile or your gui will hang.
0
 

Author Comment

by:omash
Comment Utility
i have a  compile error in the client program it is a missing return statement after readFile
i cant  find the missing braces
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now