Socket AS3 ( Receive File .TXT ) + Java Socket

Hi,
I have Java Socket sending .TXT file ( 10 MB ) . But the AS3 only gets 63 Kb . I do not understand the loss of bytes ...
Souce Java :
public void sendFile(String fileName) {
        try {
            //handle file read
            File myFile = new File(fileName);
            byte[] mybytearray = new byte[(int) myFile.length()];
            FileInputStream fis = new FileInputStream(myFile);
            BufferedInputStream bis = new BufferedInputStream(fis);
            DataInputStream dis = new DataInputStream(bis);
            dis.readFully(mybytearray, 0, mybytearray.length);
            OutputStream os = clientSocket.getOutputStream();
            byte[] fileSize = intToByte(mybytearray.length);
            byte[] clientData = new byte[(int) myFile.length() + mybytearray.length];
            System.arraycopy(fileSize, 0, clientData, 0, fileSize.length); // Copy to the file size byte array to the sending array (clientData) beginning the in the 0 index
            System.arraycopy(mybytearray, 0, clientData, 4, mybytearray.length); // Copy to the file data byte array to the sending array (clientData) beginning the in the 4 index
            DataOutputStream dos = new DataOutputStream(os);
            //dos.writeUTF(myFile.getName());
            //dos.writeInt(mybytearray.length);
            dos.write(clientData, 0, clientData.length);
            dos.flush();
AS3 Source..
private function onResponse(e:ProgressEvent):void {
  var file:File;
  var fs:FileStream;
  var fileData:ByteArray = new ByteArray();
  file = File.documentsDirectory.resolvePath("tmpReceive.txt");
  fs = new FileStream();
  fs.addEventListener(Event.CLOSE,onCloseFileReceive);
if(_socket.bytesAvailable > 0) {
  while(_socket.bytesAvailable) {
  // read the socket data into the fileData
  _socket.readBytes(fileData,0,0);
  fs.open(file, FileMode.WRITE);
  // Writing the file
  fs.writeBytes(fileData);
  fs.close();

Crypto streams, like CipherInputStream andCipherOutputStream, do not behave properly until you
issue a close() call. So if you are going to do
crypto, you will need to trap the close() before it
reaches the underlying socket streams. This is
because the close() method finalizes the cryptographic
operation. (Flush() would make more sense, no idea
why they did it this way). You do want to finalize
the crypto for any given message, but you need to trap
the close() before it hits the socket and ends the
whole affair.
I don't see anything about that in the bug database.
No matter what streams you are using, if you aregoing to keep the socket open for multiple
request-response round-trips, you need to very closely
pay attention to how much data is being sent on each
trip. Normally, you can fudge this a bit on a
request-response because the close() call on the
output stream will cause the receiving input stream to
behave more or less properly. However, a flush() will
not.Why not? I use that all the time with no problem.
A good practice is to send the content-length of
the message first, so the receiving input stream
"knows" when to stop reading, does not block, and then
can send its own bytes back the other direction.
(Where the process is repeated).
An alternative is to use two threads: read and write.
The read recieves, parses, validates and then pushes complete messages to a queue.
The write pulls messages from the queue, processes and send a result.
A variation to the above is what happens when an invalid message is received. The server can ignore it, the read can send a error response, or the read can push a message to the queue which causes the write to send a error response.

Similar Messages

  • Send many files through a socket without closing Buffered Streams?

    Hi,
    I have an application that sends/receives files through a socket. To do this, on the receiver side I have a BufferedInputStream from the socket, and a BufferedOutputStream to the file on disk.
    On the sender side I have the same thing in reverse.
    As you know I can't close any stream, ever.. because that closes the underlying socket (this seems stupid..?)
    therefore, how can I tell the receiver that it has reached the end of a file?
    Can you show me any examples that send/receive more than one file without closing any streams/sockets?

    Hi,
    As you know I can't close any stream, ever.. because that closes the underlying socket (this seems stupid..?)Its not if you want to continuosly listen to the particular port.. like those of server, you need to use ServerSocket.
    for sending multiple files the sender(Socket) can request the file to server (ServerSocket). read the contents(file name) and then return the file over same connection, then close the connection.
    For next file you need to request again, put it in loop that will be better.
    A quick Google gives me this.
    Regards,
    Santosh.

  • Send and receive file through ServerSocket

    Hi all!
    I try to send and then receive file via Server Socket but something goes wrong.
    I can send file from Client to Server, but after that I couldn't receive another file from Server to Client. What might be the problem?
    ex Client:
    public class FileClient{
      public static void main (String [] args ) throws IOException {
        int bytesRead;
        int current = 0;
        Socket sock = new Socket("localhost",13267);
        System.out.println("Connecting...");
        System.out.println("Try to send...");
        //send file
        File myFile = new File ("sourceImg.jpg");
        byte [] mybytearrayTOSend  = new byte [(int)myFile.length()];
        FileInputStream fis = new FileInputStream(myFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        bis.read(mybytearrayTOSend,0,mybytearrayTOSend.length);
        OutputStream os = sock.getOutputStream();
        System.out.println("Sending...");
        os.write(mybytearrayTOSend,0,mybytearrayTOSend.length);
        os.flush();
        System.out.println("File was sent...");
       System.out.println("Try to receive...");
        // receive file
       byte [] mybytearray  = new byte [filesize];
        InputStream is = sock.getInputStream();
        FileOutputStream fos = new FileOutputStream("source-copyImg2.jpg");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bytesRead = is.read(mybytearray,0,mybytearray.length);
        current = bytesRead;
        do {
           bytesRead =
              is.read(mybytearray, current, (mybytearray.length-current));
           if(bytesRead >= 0) current += bytesRead;
        } while(bytesRead > -1);
        bos.write(mybytearray, 0 , current);
        bos.close();
        System.out.println("File was received..");
        sock.close();
    }ex Server
    public class FileServer{
    public static void main (String [] args ) throws IOException {
        ServerSocket servsock = new ServerSocket(13267);
        while (true) {
          System.out.println("Waiting...");
          Socket sock = servsock.accept();
          System.out.println("Accepted connection : " + sock);
          // receive file
          int filesize=6022386;
          int bytesRead;
          int current = 0;
          byte [] mybytearrayIn  = new byte [filesize];
          System.out.println("Try to receive...");
          InputStream is = sock.getInputStream();
          FileOutputStream fos = new FileOutputStream("source-copyImg1.jpg");
          BufferedOutputStream bos = new BufferedOutputStream(fos);
          bytesRead = is.read(mybytearrayIn,0,mybytearrayIn.length);
          current = bytesRead;
          do {
             bytesRead =
                is.read(mybytearrayIn, current, (mybytearrayIn.length-current));
             if(bytesRead >= 0) current += bytesRead;
          } while(bytesRead > -1);
          bos.write(mybytearrayIn, 0 , current);
          long end = System.currentTimeMillis();
          bos.close();
          System.out.println("File was received...");     
          System.out.println("Try to send file...");
          // sendfile
          File myFile = new File ("sourceImg2.jpg");
          byte [] mybytearray  = new byte [(int)myFile.length()];
          FileInputStream fis = new FileInputStream(myFile);
          BufferedInputStream bis = new BufferedInputStream(fis);
          bis.read(mybytearray,0,mybytearray.length);
          OutputStream os = sock.getOutputStream();
          System.out.println("Sending...");
          os.write(mybytearray,0,mybytearray.length);
          os.flush();
          sock.close();
    }

    ex Client:
    public class FileClient{
    current = bytesRead;
    This assignment is pointless. At this line, bytesRead and 'current' are already both zero.
    do {
    bytesRead =
    is.read(mybytearray, current, (mybytearray.length-current));
    if(bytesRead >= 0) current += bytesRead;At this point, if mybytearray.length == current, you are done, and the read will return zero, so you should test for a zero return ...
    } while(bytesRead > -1);... not just a -1 return.
    ex Server
    bis.read(mybytearray,0,mybytearray.length);
    Here you are ignoring the result of the read, which can be anything between 0 and mybytearray.length. Don't do that.

  • Error in file-webservice- file (Error: java.lang.NullPointerException)

    Hi everybody,
    I have configured a file-webservice-file without BPM scenario...as explained by Bhavesh in the following thread:
    File - RFC - File without a BPM - Possible from SP 19.
    I have  used a soap adapter (for webservice) instead of rfc .My input file sends the date as request message and gets the sales order details from the webservice and then creates a file at my sender side.
    1 communication channel for sender file
    1 for receiver soap
    1 for receiver file
    Error: java.lang.NullPointerException
    What could be the reason for this error
    thanks a lot
    Ramya

    Hi Tanaya,
    I monitored the channels in the Runtime work bench and the error is in the sender ftp channel.The other 2 channel status is "not used" in RWB.
    1 sender ftp channel
    1 receiver soap channel
    1 receiver ftp channel.
    2009-12-16 15:02:00 Information Send binary file  "b.xml" from ftp server "10.58.201.122:/", size 194 bytes with QoS EO
    2009-12-16 15:02:00 Information MP: entering1
    2009-12-16 15:02:00 Information MP: processing local module localejbs/AF_Modules/RequestResponseBean
    2009-12-16 15:02:00 Information RRB: entering RequestResponseBean
    2009-12-16 15:02:00 Information RRB: suspending the transaction
    2009-12-16 15:02:00 Information RRB: passing through ...
    2009-12-16 15:02:00 Information RRB: leaving RequestResponseBean
    2009-12-16 15:02:00 Information MP: processing local module localejbs/CallSapAdapter
    2009-12-16 15:02:00 Information The application tries to send an XI message synchronously using connection File_http://sap.com/xi/XI/System.
    2009-12-16 15:02:00 Information Trying to put the message into the call queue.
    2009-12-16 15:02:00 Information Message successfully put into the queue.
    2009-12-16 15:02:00 Information The message was successfully retrieved from the call queue.
    2009-12-16 15:02:00 Information The message status was set to DLNG.
    2009-12-16 15:02:02 Error The message was successfully transmitted to endpoint com.sap.engine.interfaces.messaging.api.exception.MessagingException: Received HTTP response code 500 : Internal Server Error using connection File_http://sap.com/xi/XI/System.
    2009-12-16 15:02:02 Error The message status was set to FAIL.
    Now, the error is internal server error.What can I do about this?
    thanks a lot
    Ramya

  • File transfer, read write through sockets in client server programming java

    Hello All, need help again.
    I am trying to create a Client server program, where, the Client first sends a file to Server, on accepting the file, the server generates another file(probably xml), send it to the client as a response, the client read the response xml, parse it and display some data. now I am successful sending the file to the server, but could not figure out how the server can create and send a xml file and send it to the client as response, please help. below are my codes for client and server
    Client side
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class XMLSocketC
         public static void main(String[] args) throws IOException
              //Establish a connection to socket
              Socket toServer = null;
              String host = "127.0.0.1";     
              int port = 4444;
              try
                   toServer = new Socket(host, port);
                   } catch (UnknownHostException e) {
                System.err.println("Don't know about host: localhost.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to host.");
                System.exit(1);
              //Send file over Socket
            //===========================================================
            BufferedInputStream fileIn = null;
              BufferedOutputStream out = null;
              // File to be send over the socket.
              File file = new File("c:/xampp/htdocs/thesis/sensorList.php");
              // Checking for the file to be sent.
              if (!file.exists())
                   System.out.println("File doesn't exist");
                   System.exit(0);
              try
                   // InputStream to read the file
                   fileIn = new BufferedInputStream(new FileInputStream(file));
              }catch(IOException eee)
                   System.out.println("Problem, kunne ikke lage fil");
              try
                   InetAddress adressen = InetAddress.getByName(host);
                   try
                        System.out.println("Establishing Socket Connection");
                        // Opening Socket
                        Socket s = new Socket(adressen, port);
                        System.out.println("Socket is clear and available.....");
                        // OutputStream to socket
                        out = new BufferedOutputStream(s.getOutputStream());
                        byte[] buffer = new byte[1024];
                        int numRead;
                        //Checking if bytes available to read to the buffer.
                        while( (numRead = fileIn.read(buffer)) >= 0)
                             // Writes bytes to Output Stream from 0 to total number of bytes
                             out.write(buffer, 0, numRead);
                        // Flush - send file
                        out.flush();
                        // close OutputStream
                        out.close();
                        // close InputStrean
                        fileIn.close();
                   }catch (IOException e)
              }catch(UnknownHostException e)
                   System.err.println(e);
            //===========================================================
            //Retrieve data from Socket.
              //BufferedReader in = new BufferedReader(new InputStreamReader(toServer.getInputStream()));
              DataInputStream in = new DataInputStream(new BufferedInputStream(toServer.getInputStream()));
              //String fromServer;
            //Read from the server and prints.
              //Receive text from server
              FileWriter fr = null;
              String frn = "xxx_response.xml";
              try {
                   fr = new FileWriter(frn);
              } catch (IOException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              try{
                   String line = in.readUTF();                    //.readLine();
                   System.out.println("Text received :" + line);
                   fr.write(line);
              } catch (IOException e){
                   System.out.println("Read failed");
                   System.exit(1);
            in.close();
            toServer.close();
    public class XMLSocketS
          public static void main(String[] args) throws IOException
              //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4444);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
              while (true)
                        try
                             clientLink = serverSocket.accept();
                           System.out.println("Server accepts");
                             BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             // close the link to client
                             clientLink.close();                         
                             // close InputStream
                             inn.close();                         
                             // flush
                             ut.flush();                         
                             // close OutputStream
                             ut.close();     
                             //Sending response to client     
                             //============================================================
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
    }

    SERVER
    import java.net.*;
    import java.io.*;
    public class XMLSocketS
          public static void main(String[] args) throws IOException
                   //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4545);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
                  try
                             clientLink = serverSocket.accept();
                         System.out.println("Server accepts the client request.....");
                         BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             ut.flush();                         
                             //Sending response to client     
                             //============================================================
                             BufferedInputStream ftoC = null;
                             BufferedOutputStream outtoC = null;
                             // File to be send over the socket.
                             File file = new File("c:/xampp/htdocs/thesis/user_registration_response.xml");
                             try
                                  // InputStream to read the file
                                   ftoC = new BufferedInputStream(new FileInputStream(file));
                             }catch(IOException eee)
                             {System.out.println("Problem reading file");}
                             // OutputStream to socket
                             outtoC = new BufferedOutputStream(clientLink.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int noRead;
                             //Checking if bytes available to read to the buffer.
                             while( (noRead = ftoC.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  outtoC.write(buffer, 0, noRead);
                             outtoC.flush();
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
          }CLIENT SIDE
    import java.io.*;
    import java.net.*;
    public class XMLSocketC
              @SuppressWarnings("deprecation")
              public static void main(String[] args)
                   // Server: "localhost" here. And port to connect is 4545.
                   String host = "127.0.0.1";          
                   int port = 4545;
                   BufferedInputStream fileIn = null;
                   BufferedOutputStream out = null;
                   // File to be send over the socket.
                   File file = new File("c:/xampp/htdocs/thesis/sensorList.xml");
                   try
                        // InputStream to read the file
                        fileIn = new BufferedInputStream(new FileInputStream(file));
                   }catch(IOException eee)
                   {System.out.println("Problem");}
                   try
                             System.out.println("Establishing Socket Connection");
                             // Opening Socket
                             Socket clientSocket = new Socket(host, port);
                             System.out.println("Socket is clear and available.....");
                             // OutputStream to socket
                             out = new BufferedOutputStream(clientSocket.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int numRead;
                             //Checking if bytes available to read to the buffer.
                             while( (numRead = fileIn.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  out.write(buffer, 0, numRead);
                             // Flush - send file
                             out.flush();
                             //=======================================
                             DataInputStream in = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
                             BufferedWriter outf = new BufferedWriter(new FileWriter("c:/xampp/htdocs/received_from_server.txt",true));
                             String str;
                             while(!(str = in.readLine()).equals("EOF")) {     
                                  System.out.println("client : Read line -> <" + str + ">");
                                  outf.write(str);//Write out a string to the file
                                  outf.newLine();//write a new line to the file (for better format)
                                  outf.flush();
                             //=======================================
                             // close OutputStream
                             out.close();
                             // close InputStrean
                             fileIn.close();
                             // close Socket
                             clientSocket.close();
                        }catch (IOException e)
                        {System.out.println("Exception.");}
         Could you please point where am I doing the stupid mistake, client to server is working properly, but the opposite direction is not.
    Thanks

  • Java receive files from different station ??

    Hi,
    I would like that a station can receive files from different stations in the same time.
    For that, I use multi-threading (with different socket TCP). I have just a problem, sometimes files received are empty or contains just the last line of file. I don't know why, I saw all datagrams on the network but at reception sometimes it reads just the end.
    The class to receive file functions when it receives just one file, but when files comes at the same time there are some problem.
    Is there a problem of thread ? (I start a thread but I don't know where stop it) or a problem in my class for receive file:
    For sending a file:
    while((len = fis.read(buffer,0,1024))!= -1)
              os.write(buffer, 0, len);
                   new LogFile().writeLogFileError     
    For receiveing file:
    while((len = is.read(buffer,0,1024))>=0)
    fos.write(buffer, 0, len);
    //when theres a problem, I receive -1 the first time, but I am sure data are sent to this station
    Is someone had same problem ?
    Thank you
    Maryline

    Maryline,
    its probably a better idea to use Stream Sockets, as opposed to datagrams, as the datagrams can be delivered in any order (hence end of file so soon possibly).
    On the Server Station do the following:
    import java.net.*;
    import java.io.*;
    private final int SERVER_PORT = 4567;
    private final int SERVER_BACKLOG = 100
    ServerSocket  server = new ServerSocket( SERVER_PORT, SERVER_BACKLOG );
    while (true) {
      Socket s = server.accept();
      //Start a new thread and pass the Socket s to it.
    }You also need to create ObjectInputStreams and ObjectOutputStreams to read and write the data
    ObjectInputStream input = new ObjectInputStream( s.getInputStream() );
    ObjectOutputStream output = new ObjectOutputStream( s.getOutputStream() );
    output.flush();On the client, you use
    Socket s = new Socket( SERVER_MACHINE_NAME, SERVER_PORT )
    ObjectOutputStream output = new ObjectOutputStream( s.getOutputStream
    output.flush();
    ObjectInputStream input = new ObjectInputStream( s.getInputStream() );
    () );You can then use
    output.writeObject( ANY_SERIALIZABLE_JAVA_OBJECT );to send the object, and
    JAVA_OBJECT_TYPE myObject = (JAVA_OBJECT_TYPE) input.readObject();to recieve the object.
    If its text data, you could read the data into a string field and send it
    I hope this gives you some ideas to hepl towards your solution
    Guy

  • File Connection and Socket Connection in nokia 7710

    Hello,
    i want to transfer some data from my PC to Nokia 7710 either using File Transfer or socket connection
    For file transfer, where do i need to put my file i.e. which files does nokia 7710 allow j2me programs to access? Is is ok if the file i transfer is a plain txt file? i am using jsr 75 api for reading from the file, so what file location will i give in my program, in Nokia 7710, there are two memory drives Device and Memory Stick, so how can i access these files via a j2me program running on the cell?
    If i use socket connection, how will the phone recognize PC's ipaddress? Do i need to configure it? Also my Nokia 7710 is connected to the PC via a cable attached to USB port, so what port numbers do i specify in my j2me client program that will run on the phone and normal java server program that will run on the PC
    please help me out, this is very important for me
    thank you

    Hi Steve, Would you mind to give a a piece of code to solve this problem
    This is my code :
                              is  = sc.openInputStream();
                os = sc.openOutputStream();
                os.write(("HELO there" + "\r\n").getBytes());
                os.write(("EHLO" + "\r\n").getBytes());
                os.write(("AUTH LOGIN" + "\r\n").getBytes());
                os.write(("dHVnYXNha2hpci50cmlhZGl0eWFAZ21haWwuY29t" + "\r\n").getBytes());
                os.write(("dGEuZW1haWxjbGllbnQ=" + "\r\n").getBytes());
                os.write(("MAIL FROM:<"+ from +">\r\n").getBytes());
                os.write(("RCPT TO:<"+ to + ">\r\n").getBytes());
                os.write("DATA\r\n".getBytes());
                       // stamp the msg with date
                os.write(("Date: " + new Date() + "\r\n").getBytes());
                os.write(("From: "+from+"\r\n").getBytes());
                os.write(("To: "+to+"\r\n").getBytes());
                os.write(("Subject: "+subject+"\r\n").getBytes());
                os.write((msg+"\r\n").getBytes()); // message body]
                os.write(".\r\n".getBytes());
                os.write("QUIT\r\n".getBytes());
                              StringBuffer sb = new StringBuffer();
                              int ch = 0;
                while((ch = is.read()) != -1) {
                   sb.append((char) ch);
                si.setText("SMTP server response - " + sb.toString());but it doesn't work,...
    i try to connect smtp gmail with smtp server : smtp.gmail.com and port : 465 (Use SSL)
    regards
    triaditya

  • File transfer via socket problem (with source code)

    I have a problem with this simple client/server filetransfer program. When I run it, only half the file is transfered via the net? Can someone point out to me why this is happening?
    Client:
    import java.net.*;
    import java.io.*;
         public class Client {
         public static void main(String[] args) {
              // IPadressen til server
              String host = "127.0.0.1";
              int port = 4545;
              //Lager streams
              BufferedInputStream fileIn = null;
              BufferedOutputStream out = null;
              // Henter filen vi vil sende over sockets
              File file = new File("c:\\temp\\fileiwanttosend.jpg");
    // Sjekker om filen fins
              if (!file.exists()) {
              System.out.println("File doesn't exist");
              System.exit(0);
              try{
              // Lager ny InputStream
              fileIn = new BufferedInputStream(new FileInputStream(file));
              }catch(IOException eee) {System.out.println("Problem, kunne ikke lage fil"); }
              try{
              // Lager InetAddress
              InetAddress adressen = InetAddress.getByName(host);
              try{
              System.out.println("- Lager Socket..........");
              // �pner socket
              Socket s = new Socket(adressen, port);
              System.out.println("- Socket klar.........");
              // Setter outputstream til socket
              out = new BufferedOutputStream(s.getOutputStream());
              // Leser buffer inn i tabell
              byte[] buffer = new byte[1024];
              int numRead;
              while( (numRead = fileIn.read(buffer)) >= 0) {
              // Skriver bytes til OutputStream fra 0 til totalt antall bytes
              System.out.println("Copies "+fileIn.read(buffer)+" bytes");
              out.write(buffer, 0, numRead);
              // Flush - sender fil
              out.flush();
              // Lukker OutputStream
              out.close();
              // Lukker InputStrean
              fileIn.close();
              // Lukker Socket
              s.close();
              System.out.println("File is sent to: "+host);
              catch (IOException e) {
              }catch(UnknownHostException e) {
              System.err.println(e);
    Server:
    import java.net.*;
    import java.io.*;
    public class Server {
         public static void main(String[] args) {
    // Portnummer m� v�re det samme p� b�de klient og server
    int port = 4545;
         try{
              // Lager en ServerSocket
              ServerSocket server = new ServerSocket(port);
              // Lager to socketforbindelser
              Socket forbindelse1 = null;
              Socket forbindelse2 = null;
         while (true) {
         try{
              forbindelse1 = server.accept();
              System.out.println("Server accepts");
              BufferedInputStream inn = new BufferedInputStream(forbindelse1.getInputStream());
              BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:\\temp\\file.jpg")));
              byte[] buff = new byte[1024];
              int readMe;
              while( (readMe = inn.read(buff)) >= 0) {
              // Skriver filen til disken ut fra input stream
              ut.write(buff, 0, readMe);
              // Lukker ServerSocket
              forbindelse1.close();
              // Lukker InputStream
              inn.close();
              // flush - sender data ut p� nettet
              ut.flush();
              // Lukker OutputStream
              ut.close();
              System.out.println("File received");
              }catch(IOException e) {System.out.println("En feil har skjedd: " + e.getMessage());}
              finally {
                   try {
                   if (forbindelse1 != null) forbindelse1.close();
                   }catch(IOException e) {}
    }catch(IOException e) {
    System.err.println(e);
    }

    Hi!!
    The problem is at this line:
    System.out.println("Copies "+fileIn.read(buffer)+" bytes");
    Just comment out this line of code and see the difference. This line of code causes another "read" statement to be executed, but you are writing only the data read from the first read statement which causes approximately half the file to be send to the server.

  • Writing text to a file with a socket

    i'm writing an applet which is suppose to write the user's input to a txt file on the server's machine.
    i'm reading the information from this txt file by BufferedReader and have found out that it is not possible to use BufferedWriter to write in a similar fashion.
    in postings i have seen that i need to use one of 3 methods. 1) sign my applet, 2) servlets 3) sockets.
    i have choosen to use sockets, but i cannot figure out how to print the information i want to send, to the particular file.
    heres the code i have.... pretty much taken straight off of this tutorial
    http://java.sun.com/docs/books/tutorial/networking/sockets/readingWriting.html
    Socket echoSocket = null;
    PrintWriter out = null;
    try {
    echoSocket = new Socket(server, 8080);
    out = new PrintWriter(echoSocket.getOutputStream(), true);
    } catch (UnknownHostException e) {
    e.printStackTrace();
    System.exit(1);
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(1);
    out.println("line");
    out.flush();
    out.close();
    echoSocket.close();
    i also don't think that i have the proper name of the server defined. i know that the socket connects to the server, but i don't believe it is connecting in the right position.
    i.e. if the server name is "fred" and where the variable server is, i put "fred"....it connects. but, i don't have my files stored directly on fred, they are in subdirectories of "fred" and i can't figure out how i will go about changing the variable server, in order to reach these subdirectories.
    i hope this isn't too confusing
    thanks
    Andy

    do sockets need to have a server program running on the server?

  • Fast file transfer via sockets

    Hi,
    I have made little program that sends files via lan to my other computer using sockets (ServerSocket and Socket). When I code my program to use only FileInputStream and FileOutputStream throught the sockets I get only speed about 100Kbs even when I run them in localhost.
    I would really like to have examples of faster way to send and receive files throught sockets? Any samples using buffers or compressing data would be very nice. Thank you very much in advance!
    Sincerely,
    Lauri Lehtinen

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    * FileServer.java
    * Created on January 18, 2005, 2:21 PM
    * @author  Ian Schneider
    public class FileServer {
        static class Server {
            Socket client;
            public Server() throws Exception {
                ServerSocket s = new ServerSocket(12345);
                while (true) {
                    client = s.accept();
                    File dest = new File(System.getProperty("java.io.tmpdir"),"transfer.tmp");
                    InputStream data = client.getInputStream();
                    OutputStream out = new FileOutputStream(dest);
                    byte[] bytes = new byte[1024];
                    int l = 0;
                    int cnt = 0;
                    long time = System.currentTimeMillis();
                    while ( (l = data.read(bytes)) >= 0) {
                        cnt += l;
                        out.write(bytes,0, l);
                    int kb = cnt / 1024;
                    int sec = (int) (System.currentTimeMillis() - time) / 1000;
                    System.out.println("transfered " + kb/sec);
                    out.flush();
                    out.close();
                    client.close();
        static void writeToServer(String fileName) throws Exception {
            Socket s = new Socket("localhost",12345);
            OutputStream out = s.getOutputStream();
            FileInputStream in = new FileInputStream(fileName);
            byte[] bytes = new byte[1024];
            int l = 0;
            while ( (l = in.read(bytes)) >= 0) {
                out.write(bytes,0,l);
            out.flush();
            out.close();
            in.close();
        public static final void main(String[] args) throws Exception {
            if (args[0].equals("server")) {
                new Server();
            } else {
                writeToServer(args[1]);
    }You may see improvements by buffering these. I didn't bother testing.

  • File thansfer through socket problem

    i am writing server /client program, where the server wait for client request to send or receive file through socket.
    can i use 1 socket to handle the request (client want to send or download file) and file data transfer?
    if yes, how to handle the beginging of file transfer after receive a request?
    and how can server know when the file transfer is completed?

    This tutorial should help:
    http://java.sun.com/docs/books/tutorial/networking/index.html

  • Reading/Writing Multiple Files From/To Socket

    I'm have a problem in recognizing end of file in socket.
    when I write files one after another using object input stream wrapped on the socket's input stream.
    on one side:
    while((n = send_file_input_stream[ i ].read(buff)!=-1)
    socket_output_stream.write(buff,0,n)
    on the other side:
    while((n = socket_input_stream.read(buff)!=-1)
    recv_file_output_stream[ i ].write(buff,0,n)
    this process happens for i=1..N files
    1) how can i signal the socket That EOF occures ?
    2) how can the recieving socket stream recognize it?
    3) Is there a simple mechnism for transffering files in java
    from dir to dir from disk to socket ?
    like copy(InputStream from,OutputStram to)
    Thanks
    Joseph

    one way is to write something as an end of file marker after each file, say character 255, just make sure you escape any 255's in the file (say by sending two 255's)
    The other end then needs to look for the 255's, if it gets one on its own its the end of the file. If it get's two together its a single 255 thats part of the file.
    If that seems a bit complicated you could send a header with the count of bytes before each file, the receiving end then just has to count bytes.
    Another way is to use a new connection for each file (probably also the easiest)

  • Detect "end of file" while send n numbers files over a socket?

    Hi!
    I�m trying to find a way to detect "end of file" while send n numbers files over a socket.
    What i'm looking for is how to detect on the client side when the file i�m sending is downloaded.
    Here is the example i�m working on.
    Client side.
    import java.io.*;
    import java.net.*;
    public class fileTransfer {
        private InputStream fromServer;
        public fileTransfer(String fileName) throws FileNotFoundException, IOException {
            Socket socket = new Socket("localhost", 2006);
            fromServer = socket.getInputStream();
            for(int i=0; i<10; i++)
                receive(new File(i+fileName));
        private void receive(File uploadedFile) throws FileNotFoundException, IOException {
            uploadedFile.createNewFile();
            FileOutputStream toFile = new FileOutputStream(uploadedFile);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fromServer.read(buffer)) != -1) {
                toFile.write(buffer, 0, bytesRead);
        public static void main(String[] args) {
            try {
                new fileTransfer("testa.jpg");
            } catch (Exception ex) {ex.printStackTrace();}
    }Server side.
    import java.io.*;
    import java.net.*;
    public class fileTransferSend {
        Socket serv = null;
        OutputStream toClient;
        public fileTransferSend(String fileName) throws FileNotFoundException, IOException {
            StartServer();       
            for(int i =0; i<10; i++)
                send(new File(fileName));
        public void StartServer() throws IOException {
            ServerSocket ssocket = new ServerSocket(2006);
            System.out.println("Waiting for incomming");
            serv = ssocket.accept();
            System.out.println("incomming");
            toClient = serv.getOutputStream();
        private void send(File f) throws FileNotFoundException, IOException {
            if(f.exists() && f.canRead()) {
                FileInputStream fromFile = new FileInputStream(f);
                try {
                    byte[] buffer = new byte[4096]; // 4K
                    int bytesRead = 0;
                    System.out.println("sending: "+f.getName());
                    while ((bytesRead = fromFile.read(buffer)) != -1) {
                        toClient.flush();
                        toClient.write(buffer, 0, bytesRead);
                finally {
                    //toClient.close();
                    fromFile.close();
            } else {
                System.out.println("no files");
        public static void main(String[] args) {
            try {
                new fileTransferSend("test.jpg");
            }catch(Exception e) {e.printStackTrace();}
    I know that the client never reads -1 becuase i doesn�t close the stream.
    Is there anyway to tell the client that the file is downloaded?

    A common (and easy) TCP/IP protocol is to send length, followed by data.
    Because TCP/IP is a stream-oriented protocol, a receiver can never absolutely determine where the first packet ends and the second packet begins. So it is common to send the length of the packet, followed by the packet itself.
    In your case, you could send length of file, followed by file data. It should be fairly easy to obtain file length and send that as a 32-bit (or 64-bit value). Here is an idea (not code) for the receiver:
    receive (4) // where 4 = number bytes to receive
    unsigned length = convert 4 bytes to unsigned integer
    while (length != 0)
    n = receive ( length ) // where n = number bytes actually received, and length = number bytes desired
    Or, you can use the concept of an "Escape" character in the stream. Arbitrarily choose an ESCAPE character of 0x1B (although it could be any 8-bit value). When the receiver detects an ESCAPE char, the next character can be either control or data. So for end of file you might send 0x1B 0x00. If the byte to be sent is 0x1B, then send 0x1B 0x1B. The receiver would look something like this:
    b = read one byte from stream
    if (b == 0x1B)
    b = read one byte from stream
    if (b == 0x00) then end of file
    else place b in buffer
    else
    place b in buffer
    Later.

  • Java socket - unsure road to take!

    Hi all,
    We have an application requiring data transfer from a JSP Web application (socket client) and a stand-alone java application (socket server).
    This java stand-alone app communicates to an industrial microcontroller connected to the RS-232 serial port.
    When this java apps received a command from the JSP web app, it cannot service any other command from other uses, since there is just one RS-232 serial port on the computer. We would like to rely on the java & network environment to buffer additional commands receive simultaneously, as opposed to write code on the java socket server to handle this. In other works, our java stand-alone operates in an assynchronous, single-task mode.
    We are unsure which approach to take as far as java socket goes:
    1) simple socket server/client;
    2) multithread socket
    3) pooled
    Can anyone advise us.
    Thank you
    Trajano

    Hi Pete,
    1) Yes, we can have more than one user trying to access the micro-controllers, because we have in reality a network of micro-controllers connected to the single RS-232 computer port via a RS-485 to RS-232 converter;
    2) If a second user tries to issue a command to micro-controller, I would prefer for the java socket/environment to take care of the buffering, by just delaying the response, until the first user gets its command serviced
    3) If there is 1 user, him/her might issue several commands at the same time, by opening several JSP pages;
    4) No the controllers can service any instruction coming up at any time. The protocol is master/slave. The java app issues a request and the micro-controlle replies back and ready to accept any other request.
    ISSUE: My preference is for the system to take care of commands arriving at the socket server.
    This java app has two threads:
    1) Thread1 is the java socket server and upon receiving a command it will update three (3) properties:
    micro-controller address, command and product code
    2) Thread32 will be responsible for polling the 3 properties to check if they've changed. Upon detecting a change, it will build the data string and send to the RS-232 serial port.
    Any ideas/suggestions.
    Thanks in advance for any assistance.
    Regards

  • File transfering using Sockets

    can anybody help me to find the simple sample code for file transfering. i m new to java and having problem in client server assignment. sending message (chatting) is done, but i still need file transfering part. only one file at one time is good enough.
    thanks.
    moe

    Since you're asking for help with your homework, I won't give you any code but I will point you in the right direction. Sockets can be used to stream data and files also use sockets. If you put the two together, you'll be able to stream your files between JREs.
    Shaun

Maybe you are looking for