Avatar billede aslan Nybegynder
04. august 2002 - 18:16 Der er 10 kommentarer og
1 løsning

Oprette forbindelse via socket og downloade?

Er der nogen her der kan vise mig hvordan jeg opretter forbindelse til en server og downloader en fil fra den via socket? Så ville jeg være en megt glad mand:-)
Avatar billede webster Nybegynder
04. august 2002 - 19:27 #1
kan du ikke først lige uddybe hvilken slags server du mener før jeg svarer på noget forkert =)
Avatar billede aslan Nybegynder
04. august 2002 - 19:41 #2
Det er en linux server som har adressen :

http://212.242.120.84/
Avatar billede webster Nybegynder
04. august 2002 - 20:05 #3
okay jeg tager at du altså vil hente en fil fra en webserver =) du kan bruge en URLConnection til det formål. Her noget eksempel kode (ikke noget jeg har testet men det viser princippet):

URL remoteFile = null;
URLConnection URLCon = null;
InputStream in = null;

File outputFile = null;
FileOutputStream outStream = null;

try{
    outputFile = new File("c:\download\minFil.jpg");
    outStream = new FileOutputStream(outputFile);

    remoteFile = new URL("http://212.242.120.84/minFil.jpg");
    URLCon = remoteFile.openConnection();
    in = URLCon.getInputStream();

    int c;
    while ((c = in.read()) != -1){
        outStream.write(c);
    }
   
    outStream.close();

}catch (Exception e){
    //Noget error handling her
}


Du kan evt. tilføje lidt mere cleanup efter at outStream er lukket.
Avatar billede carstenknudsen Nybegynder
04. august 2002 - 20:19 #4
Du har ikke specificeret hvilken protocol
der skal benyttes til at fortælle serveren
hvad du ønsker, på hvilken port der skal
kommunikeres etc.
For at åbne en socket til serveren kan
du skrive:
InetAddress address = InetAddress.getByName("212.242.120.84");
Socket socket = new Socket( address, port );
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter( os );
BufferedWriter bw = new BufferedWriter( osw );
bw.write("din kommando til serveren");
//hvor du fortæller hvad du vil downloade
bw.flush();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("lokalfil");
byte[] buffer = new byte[ 1024 ];
int bytes_read;
while ((bytes_read=is.read(buffer) != -1 ) {
fos.write(buffer,0,bytes_read);
}
fos.close();
socket.close();

Jeg har ikke benyttet buffering alle de
steder det bør gøres etc. Hvis du har
mere konkret information om protokollen
så skriv om det. Hvis det er en normal
webserver er det meget lettere at downloade
via en url end det er via en socket.
Avatar billede aslan Nybegynder
04. august 2002 - 20:36 #5
Ok tak for jeres forslag.. hvordan ville det være muligt at bruge en JFileChooser til at hente en fil fra en mappe efter at have fået forbindelse til serveren?
Avatar billede carstenknudsen Nybegynder
04. august 2002 - 20:59 #6
Ang. JFileChooser: nej det vil det ikke,
men hvis du kan få serveren til at fortælle
hvilke filer der kan downloades kan du
godt fake det, men direkte, nej, det kan
du kun fra det lokale filsystem.
Du har endnu ikke fortalt hvilken protokol
der benyttes.
Avatar billede aslan Nybegynder
04. august 2002 - 22:25 #7
Hvad hvis jeg bruger en signed applet vil clienten så kunne bruge en JFilechooser til at hente en fil fra serveren ? Måske fra samme mappe fra hvor appleten findes? Det må da kunne lade sig gøre...
Avatar billede mfj1 Nybegynder
04. august 2002 - 23:45 #8
Hvis appletten er signed mener jeg bestemt at du kan få adgang til klientens filsystem.. Ser lige efter et eksempel :-)
Avatar billede carstenknudsen Nybegynder
05. august 2002 - 09:33 #9
Du kan stadig ikke få adgang til serverens filsystem, du
kan bede serveren sende dig en list med navnene på
filerne der må downloades, hvorefter du kan lave
en snyde JFileChooser lokalt, en signed applet kan
ikke afhjælpe det problem.
Avatar billede aslan Nybegynder
05. august 2002 - 09:39 #10
Hvordan ville det se ud carstenknudsen hvis jeg skulle følge dit eksampel med den snyde JFileChooser?
Avatar billede carstenknudsen Nybegynder
05. august 2002 - 10:00 #11
Først og fremmest skal der på serveren ligge en fil
der indeholder navnene på alle de filer der må/kan
downloades. Klienten udbeder sig så den fil og
har nu en liste med filnavne den kan downloade.
Nu skal du så oprette en snyde-filechooser hvor
du kan vælge mellem de angivne navne. Jeg ville
ikke personlig lave en JFileChooser, men smide
navnene i en JList som kan vises for brugeren
der så kan afmærke de filer der skal hentes.
Her er et lettere modificeret eksempel på en klasse
jeg bruger præcis til samme formål. Den kan kortes
væsentligt ned, idet der bla. er verficeret download
hvilket nok ikke er nødvendigt.Det eneste klassen
kræver er at filen "filelist" ligger på webserveren
og at der naturligvis kører en webserver på port 80.
import java.io.*;
import java.util.zip.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.security.*;
import java.security.spec.*;
/**
* The FileDownloader class is a special class designed for use
* by the Janet system to download files from a designated
* web server (see {@link Janet.StandardValues#WebServerName}).
* The communication lines use port
* {@link Janet.StandardValues#WebServerPort}.
* It is easy to modify the class to work in other applications.
* Note that the class also works as a stand-alone application.
* <br><b>Example of use:</b>
* <pre>
* FileDownloader downloader = new FileDownloader();
* downloader.show();
* </pre>
* @author Carsten Knudsen
*/

    /**
    * Private constructor for class FileDownloader.
    **/
    private FileDownloader( boolean standAlone ) {
        super( "FileDownloader" );
        this.standAlone = standAlone;
        try {
            Socket socket = new Socket( StandardValues.WebServerName,
                                        StandardValues.WebServerPort );
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader( is );
            BufferedReader fromserver = new BufferedReader( isr );
            OutputStream os = socket.getOutputStream();
            PrintWriter toserver = new PrintWriter( os );
            toserver.print( "GET /~janet/filelist HTTP/1.0\n\n" );
            toserver.flush();
            String line;
            boolean ready = false;
            java.util.Vector vector = new java.util.Vector();
            while ( ( line = fromserver.readLine() ) != null ) {
                if ( line.equals( "" ) ) {
                    ready = true;
                } // if
      else if ( ready ) {
                    vector.add ( line );
                } // else if
            } // while
            socket.close();
            names = new String[ vector.size() ];
            for (int i = 0; i < names.length; i++) {
                names[ i ] = (String)vector.get( i );
            } // for
        } // try
        catch ( UnknownHostException uhe ) {
            JOptionPane.showMessageDialog( null,
                                          "Unknown host exception: " + uhe.getMessage(),
                                          "Error",
                                          JOptionPane.ERROR_MESSAGE );

            return;
        } // catch
  catch ( Exception ioe ) {
            JOptionPane.showMessageDialog( null,
                                          "IO exception: " + ioe.getMessage(),
                                          "Error",
                                          JOptionPane.ERROR_MESSAGE );

            return;
        } // catch
        text = new JTextArea( 10, 10 );
        text.setEditable( false );
        text.append( "To select a file for downloading" +
                    StandardValues.CR +
                    "  press CTRL and left mouse button over file." +
                    StandardValues.CR );
        text.append( "To select a contiguous range of files for downloading" +
                    StandardValues.CR +
                    "  click on top file then press SHIFT and click on bottom file." +
                    StandardValues.CR );
        list = new JList( names );
        list.setFont( new Font( "Monospaced", Font.PLAIN, 12 ) );
        list.setVisibleRowCount( 15 );
      list.setVisibleRowCount( 15 );
        list.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
        getContentPane().setLayout( new BorderLayout() );
        getContentPane().add( new JScrollPane( list ), "Center" );
        getContentPane().add( new JScrollPane( text ), "North" );
        JPanel buttonPanel = new JPanel();
        downloadButton = new JButton( downloadText );
        downloadButton.setMargin( inset );
        downloadButton.setToolTipText( "Download the selected files." );
        downloadButton.setEnabled( false );
        verifyButton = new JButton( verifyText );
        verifyButton.setMargin( inset );
        verifyButton.setToolTipText( "Download the selected files with digital signature check." );
        verifyButton.setEnabled( false );
        closeButton = new JButton( closeText );
        closeButton.setMargin( inset );
        closeButton.setToolTipText( "Close the FileDownloader down." );
        selectAllButton = new JButton( selectAllText );
        selectAllButton.setMargin( inset );
        selectAllButton.setToolTipText( "Select all files in the file list." );
        unselectAllButton = new JButton( unselectAllText );
        unselectAllButton.setMargin( inset );
    unselectAllButton.setToolTipText( "Unselect all files in the file list." );
        ActionListener listener = new ActionListener() {
            public void actionPerformed( ActionEvent ae ) {
                if ( ae.getActionCommand().equals( downloadText ) ) {
                    download();
                } // if
                else if ( ae.getActionCommand().equals( verifyText ) ) {
                    verifydownload();
                } // else if
                else if ( ae.getActionCommand().equals( closeText ) ) {
                    dispose();
                } // else if
                else if ( ae.getActionCommand().equals( selectAllText ) ) {
                    int[] indices = new int[ names.length ];
                    for (int i = 0; i < names.length; i++) {
                        indices[ i ] = i;
                    } // for
                    list.setSelectedIndices( indices );
                } // else if
                else if ( ae.getActionCommand().equals( unselectAllText ) ) {
                    list.clearSelection();
                } // else if
          } // actionPerformed
            }; // ActionListener
        ListSelectionListener listSelectionListener = new ListSelectionListener() {
                public void valueChanged( ListSelectionEvent lse ) {
                    if ( list.getMinSelectionIndex() < 0 ) {
                        downloadButton.setEnabled( false );
                        verifyButton.setEnabled( false );
                    } // if
                    else {
                        downloadButton.setEnabled( true );
                        verifyButton.setEnabled( true );
                    } // else
                } // valueChanged
            }; // ListSelectionListener
        list.addListSelectionListener( listSelectionListener );
        downloadButton.addActionListener( listener );
        verifyButton.addActionListener( listener );
        closeButton.addActionListener( listener );
        selectAllButton.addActionListener( listener );
        unselectAllButton.addActionListener( listener );
        buttonPanel.add( downloadButton );
        buttonPanel.add( verifyButton );
        buttonPanel.add( selectAllButton );
        buttonPanel.add( unselectAllButton );
        buttonPanel.add( closeButton );
        getContentPane().add( buttonPanel, "South" );
        setSize( 600, 600 );
    } // constructor

    private void download() {
        InputStream instream = null;
        OutputStream outstream = null;
        for (int i = 0; i < names.length; i++) {
            if ( list.isSelectedIndex( i ) ) {
                try {
                    URL url = new URL( "http://" + StandardValues.WebServerName + "/~janet/" + names[ i ] );
                    instream = url.openStream();
                    outstream = new FileOutputStream( names[ i ] );
                    byte[] buffer = new byte[ 4096 ];
                    int bytes_read, total_bytes = 0;
                    while ( ( bytes_read = instream.read( buffer ) ) != -1 ) {
                        outstream.write( buffer, 0, bytes_read );
                        total_bytes += bytes_read;
                    } // while
                  text.append( "File " + names[ i ] + " downloaded (" + total_bytes +
                                " bytes read)." + StandardValues.CR );
                } // try
                catch ( UnknownHostException uhe ) {
                    JOptionPane.showMessageDialog( null,
                                                  "Unknown host exception: " + uhe.getMessage(),
                                                  "Error",
                                                  JOptionPane.ERROR_MESSAGE );

                } // catch
                catch ( IOException ioe ) {
                    JOptionPane.showMessageDialog( null,
                                                  "IO exception: " + ioe.getMessage() + StandardValues.CR +
                                                  "Occured while reading " + names[ i ],
                                                  "Error",
                                                  JOptionPane.ERROR_MESSAGE );
                } // catch
                finally {
                    try {
                      if ( instream != null ) instream.close();
                    } // try
                    catch ( Exception e ) {}
                    try {
                        if ( outstream != null ) outstream.close();
                    } // try
                    catch ( Exception e ) {}
                } // finally
            } // if
        } // for
    } // download

    private void verifydownload() {
        PublicKey publicKey = null;
        try {
            URL keyURL = new URL( "http://" + StandardValues.WebServerName + "/~janet/janetpublickey" );
            InputStream is = keyURL.openStream();
            int length = 0;
            while ( is.available() != 0 ) {
                byte b = (byte)is.read();
                length++;
            } //
          is.close();
            is = keyURL.openStream();
            byte[] encodedKey = new byte[ length ];
            is.read( encodedKey, 0, length );
            is.close();
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec( encodedKey );
            KeyFactory keyFactory = KeyFactory.getInstance( "DSA" );
            publicKey = keyFactory.generatePublic( publicKeySpec );
        } // try
        catch ( GeneralSecurityException gse ) {
            JOptionPane.showMessageDialog( null,
                                          "General security exception: " + gse.getMessage() + StandardValues.CR,
                                          "Error",
                                          JOptionPane.ERROR_MESSAGE );
            return;
        } // catch
        catch ( IOException ioe ) {
        JOptionPane.showMessageDialog( null,
                                          "IO exception: " + ioe.getMessage() + StandardValues.CR,
                                          "Error",
                                          JOptionPane.ERROR_MESSAGE );
            return;
        } // catch
        InputStream instream = null;
        OutputStream outstream = null;
        for (int i = 0; i < names.length; i++) {
            if ( list.isSelectedIndex( i ) ) {
                try {
                    /* Create a Signature object and initialize it with the public key */
                    Signature dsa = Signature.getInstance( "SHA1withDSA" );
                    dsa.initVerify( publicKey );
                    URL url = new URL( "http://servername/~username/" + names[ i ] );
                    instream = url.openStream();
                    outstream = new FileOutputStream( names[ i ] );
                    byte[] buffer = new byte[ 4096 ];
                    int bytes_read, total_bytes = 0;
                    while ( ( bytes_read = instream.read( buffer ) ) != -1 ) {
                        outstream.write( buffer, 0, bytes_read );
                        total_bytes += bytes_read;
                        dsa.update( buffer, 0, bytes_read );
                    } // while
                    text.append( "File " + names[ i ] + " downloaded (" + total_bytes +
                                " bytes read)." + StandardValues.CR );
                    /* Read associated signature */
                    url = new URL( "http://" + StandardValues.WebServerName + "/~janet/" + names[ i ] + ".sig" );
                    try {
                        instream = url.openStream();
                        int length = 0;
                        while ( instream.available() != 0 ) {
                            byte b = (byte)instream.read();
                            length++;
                        } //
                        instream.close();
                        byte[] signature = new byte[ length ];
                        instream = url.openStream();
                        instream.read( signature, 0, length );
                        instream.close();
                      /* attempt to verify signature */
                        boolean verified = dsa.verify( signature );
                        if ( verified ) {
                            text.append( "Signature was verified." + StandardValues.CR );
                        } // if
                        else {
                            text.append( "Signature could not be verified." + StandardValues.CR );
                        } // else
                    } // try
                    catch ( IOException ioe ) {
                        text.append( "No signature file found." + StandardValues.CR );
                    } // catch
                } // try
                catch ( GeneralSecurityException gse ) {
                    JOptionPane.showMessageDialog( null,
                                                  "General security exception: " + gse.getMessage() + StandardValues.CR,
                                                  "Error",
                                                  JOptionPane.ERROR_MESSAGE );
                } // catch
            catch ( UnknownHostException uhe ) {
                    JOptionPane.showMessageDialog( null,
                                                  "Unknown host exception: " + uhe.getMessage(),
                                                  "Error",
                                                  JOptionPane.ERROR_MESSAGE );

                } // catch
                catch ( IOException ioe ) {
                    JOptionPane.showMessageDialog( null,
                                                  "IO exception: " + ioe.getMessage() + StandardValues.CR,
                                                  "Error",
                                                  JOptionPane.ERROR_MESSAGE );
                } // catch
                finally {
                    try {
                        if ( instream != null ) instream.close();
                    } // try
                    catch ( IOException ioe ) {}
                    try {
                        if ( outstream != null ) outstream.close();
                    } // try
                    catch ( IOException ioe ) {}
                } // finally
            } // if
        } // for
    } // verifydownload

    /**
    * The method disposes of the frame and exits if
    * run as a stand-alone application.
    **/
    public void windowClosing( WindowEvent e ) {
        if ( standAlone ) {
            System.exit( 0 );
        } // if
        else {
            dispose();
        } // else
    } // windowClosing

    public void windowClosed( WindowEvent e ){}
    public void windowDeactivated( WindowEvent e ) {}
    public void windowOpened( WindowEvent e ) {}
    public void windowActivated( WindowEvent e ) {}
    public void windowDeiconified( WindowEvent e ) {}
    public void windowIconified( WindowEvent e ) {}

    /**
    * Class FileDownloader works as a stand-alone application.
    **/
    public static void main( String[] args ) {
        FileDownloader downloader = new FileDownloader( true );
        downloader.show();
    } // main

} // FileDownloader
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Kurser inden for grundlæggende programmering

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester