file transfer via socket

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • spasavvas
    New Member
    • Aug 2007
    • 2

    #1

    file transfer via socket

    Hi
    I am trying to create a server – client model where client send a file and when server receive the file send back an ack msg.
    My code is:
    [PHP]
    import java.net.*;
    import java.io.*;

    class Client{
    public static void main (String[] args){

    DataInputStream input;

    BufferedInputSt ream bis;
    BufferedOutputS tream bos;
    int in;
    byte[] byteArray;

    try{
    Socket client = new Socket("127.0.0 .1", 8585);

    input = new DataInputStream (client.getInpu tStream() );

    System.out.prin tln("Server message: " +input.readUTF( ) );

    bis = new BufferedInputSt ream(new FileInputStream ("encryptAtmMsg .txt"));
    bos = new BufferedOutputS tream(client.ge tOutputStream() );
    byteArray = new byte[8192];
    while ((in = bis.read(byteAr ray)) != -1){
    bos.write(byteA rray,0,in);
    }
    bis.close();
    bos.close();

    System.out.prin tln("Server message: " +input.readUTF( ) );
    }
    catch ( Exception e ) {
    System.err.prin tln(e);
    }
    }

    }
    [/PHP]
    and
    [PHP]
    import java.net.*;
    import java.io.*;

    class Server{
    public static void main (String[] args){

    ServerSocket server;
    Socket connection;

    DataOutputStrea m output;

    BufferedInputSt ream bis;
    BufferedOutputS tream bos;

    byte[] receivedData;
    int in;
    try{
    server = new ServerSocket( 8585 );
    while ( true ) {
    connection = server.accept() ;

    output = new DataOutputStrea m (connection.get OutputStream() );

    output.writeUTF ( " ack 1" );

    receivedData = new byte[1024];
    bis = new BufferedInputSt ream(connection .getInputStream ());
    bos = new BufferedOutputS tream(new FileOutputStrea m("sss.txt")) ;
    while ((in = bis.read(receiv edData)) != -1){
    bos.write(recei vedData,0,in);
    }
    bos.close();
    output.writeUTF ( " ack 2" );
    }
    }
    catch (IOException e ) {
    System.err.prin tln(e);
    }
    }
    }
    [/PHP]
    I have this error: java.net.Socket Exception: socket closed
    Any ideas pls...
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by spasavvas
    I have this error: java.net.Socket Exception: socket closed
    Any ideas pls...
    On which side? The client or the server?

    kind regards,

    Jos

    Comment

    • spasavvas
      New Member
      • Aug 2007
      • 2

      #3
      Client give this error

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by spasavvas
        Client give this error
        Try flushing the buffered streams before you close anything. The rest of the logic
        in your code seems ok.

        kind regards,

        Jos

        Comment

        Working...