Problems sending files throught TCP sockets

I would like to transfer a file throught a tcp socket, here there is what the sender program does :
try{
     File localFile = new File("shared/"+fileName);
     DataOutputStream oos = new DataOutputStream(socket.getOutputStream());     
     DataInputStream fis = new DataInputStream(new FileInputStream(localFile));
     while(fis.available() > 0){
          oos.writeByte(fis.readByte());
     catch(Exception e){}here what the receiver program does:
     try{
     File downloadFile = new File("incoming/"+fileName);
     downloadFile.createNewFile();
     ois = new DataInputStream(connectionSocket.getInputStream());
     fos = new DataOutputStream(new FileOutputStream(downloadFile));
     while(ois.available() > 0){
          fos.writeByte(ois.readByte());
     catch(Exception e){}
}Where i m wrong? it doesnt work :( , it just create the new file in the incoming folder, but its size remains 0 byte :(
help a newbye please :D

Your problem is probably related to the use of available. This is the amount that is currently in the buffer that you can read without blocking. For network programming you should expect to have to wait for data. Second, you are copying the data one byte at a time which is not very efficient. Try something like:
// Sender
try {
    File localFile = new File("shared/"+fileName);
    OutputStream out = socket.getOutputStream();     
    InputStream fis = new FileInputStream(localFile);
    int length;
    byte[] buffer = new byte[4096];
    while((length = fis.read(buffer)) != -1)
     out.write(buffer, 0, length);
    fis.close();
    out.close();
catch(Exception e){}
// Receiver
try {
    File downloadFile = new File("incoming/"+fileName);
    IntputStream ois = connectedSocket.getIntputStream();     
    OutputStream fos = new FileOutputStream(downloadFile);
    int length;
    byte[] buffer = new byte[4096];
    while((length = ois.read(buffer)) != -1)
     fos.write(buffer, 0, length);
    fos.close();
    ois.close();
catch(Exception e){}

Similar Messages

  • Sending file through TCP/IP

    Hi all,
    I would like to know whether LabVIEW is able to send file through TCP/IP. Can anyone please enlighten me on this. Thank You
    Rgds 

    Hi taytay,
    Of course it is possible !
    Go to function palette >> Communication >> TCP ; I have never used them but here they are.
    Go to Help >> Find examples.. and search for TCP, you'll find example code
    You can also purchase the "internet toolkit" that provide ready to use FTP VIs to send or copy simple/multiple file(s).
    Hope this helps.
    When my feet touch the ground each morning the devil thinks "bloody hell... He's up again!"

  • Send file with TCP/IP

    I would like to transfer a complete file with TCP/IP form a client to a server. I have a working example of using the TCP protocol to transmit data (as a string). I attached this Client-VI to this posting. The server program does nothing more than send the received data back to the client. Is it possible to send complete files with TCP/IP instead of sending strings? If so, would you be so kind and change my VI into a new one and send it back to me?
    If somebody has another idea to solve this problem, feel free to contact me!
    I use LabVIEW 7.0Express and WindowsXP.
    Thnaks, Dennis
    Attachments:
    ipc@chip_1.vi ‏38 KB

    Hi,
    I have a set of Vis that do the job. It's a LV5 Vi and I haven't translated it yet to LV7. It's two SubVis and two Vis that show you how to run the SubVis. The client asks a file that is in the server and the server sends it back. I'm attaching the two libraries llb, the client library and the server library. Please contact me if you have questions.
    Marce
    Attachments:
    TestTCPServerGetFile.llb ‏205 KB

  • Problems sending bufferedimages through a socket

    Hi everyone,
    I've got a server program that takes a screen capture as a bufferedimage, and sends it through a socket to be saved by the client program. The programs work fine, however, whenever I'm transferring the image with the code at the bottom of this post, I notice that the collision LED on my network hub flashes and I can't figure out why (Obviously there's a collision, but I don't know what causes it or how to stop it from happening). I've googled a bit for collisions and bufferedimages, but have come up with El Zilcho. I've also gone through the IO tutorial and the Socket and BufferedImage API's, but havent learned anything to solve my problem.
    Also, As it is now, if I want multiple images, I need to disconnect and reconnect repeatedly. I tried sending multiple bufferedimages throught the socket, but get the following exception:
    java.lang.illegalargumentexception:  im == null!Does anyone know of a way where I can send multiple bufferedimages through the socket without reconnecting every single time? Thanks
    Server code:
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Dimension screenSize = toolkit.getScreenSize();
    Rectangle screenRect = new Rectangle(screenSize);
    Robot robot = new Robot();
    BufferedImage image = robot.createScreenCapture(screenRect));
    ImageIO.write(image, "jpeg", fromClient.getOutputStream());
    fromclient.shutdownOutput();
    fromclient.close();Client code:
    BufferedImage receivedImage = ImageIO.read(toServer.getInputStream)
    toServer.close();Any help would be greatly appreciated. TIA
    Jay

    Have you tried.
    ImageIO.write(image1, "jpeg", fromClient.getOutputStream());
    ImageIO.write(image2, "jpeg", fromClient.getOutputStream());
    ImageIO.write(image3, "jpeg", fromClient.getOutputStream());
    ImageIO.write(image4, "jpeg", fromClient.getOutputStream());
    ImageIO.write(image5, "jpeg", fromClient.getOutputStream());
    ImageIO.write(image6, "jpeg", fromClient.getOutputStream());
    ImageIO.write(image7, "jpeg", fromClient.getOutputStream());

  • I have a problem sending files along with thier directories to server

    The Problem is i couldnt understand the sequence in which should the file transfers will execute.....
    Here is the Code ......
    The **************Error************* i get is that it makes one dir then other one and paste one file in it after writing another file in the second loop it gives error on write UTF that Socket write Error COnnection Reset by peer
    ***************************CLIENT************************
    package oam.filemanager;
    import java.net.*;
    import java.util.*;
    import java.io.*;
    import oam.beans.*;
    public class FileClient {
    Socket socket;
    DataOutputStream dataout;
    FileBean file;
    public void SetSocket() {
    //Create socket connection
    try {
    socket = new Socket("localhost", 9898);
    dataout = new DataOutputStream(socket.getOutputStream());
    String wavfiles []=null;
    //Directory & Wavfiles Manipulation
    file=new FileBean();
    String dirs []= file.getDirsForSocket("Accounts//");
    for(int i=0;i<dirs.length;i++){
    wavfiles= file.getWavfiles("Accounts//"+dirs[i]+"//");
    //sending Username & DIR
    dataout.writeUTF(dirs);
    if (wavfiles.length==0)
    dataout.writeUTF("no");
    for (int j=0;j<wavfiles.length;j++){       
    //Sending Filename
    dataout.writeUTF(wavfiles[j]);
    //getting file to be send
    File f = new File("Accounts//"+dirs[i]+"//"+wavfiles[j]);
    int fileLength = (int) f.length();
    System.out.println("fileLength " + fileLength);
    byte data[] = new byte[fileLength]; //settting array of byte to file len
    //reading from file acha
    FileInputStream fis = new FileInputStream(f);
    // Send file length
    dataout.writeInt(fileLength); // writing file length
    dataout.flush();
    System.out.println("Length Sent .... " + fileLength);
    dataout.flush();
    // Send file
    int loop = 0;
    loop = fis.read(data);
    System.out.println("......1......" + "in loop" + loop);
    if (loop > -1) {
    dataout.write(data);
    //closeConnection();
    // output.flush();
    catch (UnknownHostException e) {
    System.out.println("Unknown host:");
    System.exit(1);
    catch (IOException e) {
    System.out.println("No I/O " + e.getMessage());
    System.exit(1);
    catch (Exception e){
    e.printStackTrace();
    public static void main(String args[]) {
    FileClient serv = new FileClient();
    serv.SetSocket();
    ******************************************SERVER*********************
    import java.io.*;
    import java.net.*;
    import java.io.*;
    class ClientThread
    implements Runnable {
    FileOutputStream output;
    DataInputStream input;
    String uname;
    String filename;
    Socket client;
    public ClientThread(Socket clientth) {
    this.client=clientth;
    public void checkdir(String dirname){
    File f =new File("..//Accounts//"+uname+"//");
    if (!f.exists()){
    f.mkdirs();
    public void run() {
    try {
    while (true) {
    input = new DataInputStream(client.getInputStream());
    uname = "";
    filename = "";
    uname = input.readUTF();
    checkdir(uname);
    filename = input.readUTF();
    if (!filename.equals("no")) {
    System.out.println("Filename Recieved of file: " + filename);
    File f = new File("..//Accounts//" + uname + "//" + filename);
    if (!f.exists()) {
    RandomAccessFile raf = new RandomAccessFile(f, "rw");
    raf.setLength(0);
    int length;
    int pack = 0;
    int fileLength = 0;
    System.out.println("User Name received...." + uname);
    System.out.println("...2a....");
    fileLength = input.readInt();
    System.out.println("...2b....");
    System.out.println("Length Receieved .... " + fileLength);
    // input.readInt();
    // input.readInt();
    byte data[] = new byte[fileLength];
    System.out.println("Length Receieved .... " + fileLength);
    input.read(data);
    raf.write(data);
    raf.close();
    System.out.println("File Receieved and Wrote at Server");
    // clientoutput.flush();
    else {
    System.err.println("File Already Exists request by " + uname);
    } //if check ends
    catch (IOException e) {
    System.out.println("in or out failed"+ e.getMessage());
    System.exit( -1); }
    public class FileServer {
    Socket client;
    ServerSocket server;
    public FileServer(){
    File f=new File("..//Accounts") ;
    if(!f.exists())
    f.mkdirs();
    public void listenSocket() {
    try {
    server = new ServerSocket(9898);
    catch (IOException e) {
    System.out.println("Could not listen on port 9898 Server Already Listening");
    System.exit( -1);
    while (true) {
    ClientThread cth;
    try {
    cth = new ClientThread(server.accept());
    Thread thr = new Thread(cth);
    thr.start();
    catch (Exception mye) {
    mye.printStackTrace();
    protected void finalize() {
    try {
    server.close();
    catch (IOException e) {
    System.out.println("Could not close socket");
    System.exit( -1);
    public static void main(String args[]) {
    FileServer serv = new FileServer();
    serv.listenSocket();

    Well Thanks a lot : jschell so nice of u helping me all through this well i sort out this problem as well...
    i wasnt sending all files at once ...........one by one the problem was the biggest file is 240 k and byte arraay couldnt accomdate it ................so now i am sending files in 4k packets any of u guys need help u can see this code how to send files in packets .................
    //**********************SERVER************************************
    package servermanager;
    import java.io.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class ClientThread
        implements Runnable {
      FileOutputStream output;
      DataInputStream input;
    DataOutputStream dataout;
      String uname;
      String filename;
      Socket client;
      JTextArea log;
      public ClientThread(Socket clientth,JTextArea mylog) {
        this.client=clientth;
        this.log=mylog;
      public void checkdir(String dirname){
      File f =new File("..//Accounts//"+uname+"//");
      if (!f.exists()){
        f.mkdirs();
      public synchronized  void  startTransfer(){
          try {
              FileOutputStream fos=null;
              input = new DataInputStream(client.getInputStream());
              uname = "";
              filename = "";
              uname = input.readUTF();
              checkdir(uname);
              filename = input.readUTF();
              File f = new File("..//Accounts//" + uname + "//" + filename);
              RandomAccessFile raf = new RandomAccessFile(f, "rw");
              raf.setLength(0);
              raf.close();
              long fileLength=0;
              byte lenbuf[]=null;
              int help =input.read();
              lenbuf = new byte[help];
              input.read(lenbuf);
              String lenz = new String(lenbuf);
              fileLength = new Integer(lenz).longValue();
              fos = new FileOutputStream (f);
              byte data[]=new byte[4096];
              int length;
              while( (length=input.read(data, 0, 4096)) > 0) {
               fos.write(data, 0, length);
              fos.close();
      log.append("\n File Recieved = ["+filename+"]:---:"+"of Size["+fileLength+"]:---:"+"By ["+uname+"]." );
        catch (IOException e) {
          log.append("\n In or Out failed"+e.getMessage());
          System.exit( -1);}
      public void run() {
        startTransfer();
    public class FileServer extends JFrame {
      int port;
      Socket client;
      ServerSocket server;
      JScrollPane textscrollpane = new JScrollPane();
      JTextArea log = new JTextArea();
      JButton clear_btn = new JButton();
      JButton stop_btn = new JButton();
      public FileServer(){
        port=9898;
        File f=new File("..//Accounts")  ;
        if(!f.exists())
         f.mkdirs();
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      public void listenSocket() {
        try {
          server = new ServerSocket(port);
        catch (IOException e) {
         log.append("\n Could not listen on port["+port+"]");
         System.exit( -1);
        while (true) {
          ClientThread cth;
          try {
            cth = new ClientThread(server.accept(),log);
            Thread thr = new Thread(cth);
            thr.start();
          catch (Exception  mye) {
         log.append("\n Thread Exception["+mye.getMessage()+"]");
      protected void finalize() {
        try {
          server.close();
        catch (IOException e) {
              log.append("\n Could not Close Socket on port["+port+"]");
          System.exit( -1);
      public static void main(String args[]) {
        FileServer serv = new FileServer();
        serv.setBounds(new Rectangle(150,150,500,300));
        serv.show();
        serv.listenSocket();
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(null);
        textscrollpane.setBounds(new Rectangle(1, 21, 489, 212));
        log.setBackground(Color.black);
        log.setForeground(Color.green);
        log.setToolTipText("Server Log");
        log.setEditable(false);
        log.setLineWrap(true);
        clear_btn.setText("Clear");
        clear_btn.addActionListener(new FileServer_clear_btn_actionAdapter(this));
        clear_btn.setBounds(new Rectangle(323, 245, 86, 13));
        clear_btn.setToolTipText("");
        stop_btn.setToolTipText("");
        stop_btn.setBounds(new Rectangle(55, 246, 86, 13));
        stop_btn.setText("Stop");
        stop_btn.addActionListener(new FileServer_stop_btn_actionAdapter(this));
        this.addWindowListener(new FileServer_this_windowAdapter(this));
        this.getContentPane().add(textscrollpane, null);
        this.getContentPane().add(stop_btn, null);
        this.getContentPane().add(clear_btn, null);
        textscrollpane.getViewport().add(log, null);
        log.setText("Server Initiated Listening on Port [9898]...");
      void stop_btn_actionPerformed(ActionEvent e) {
        System.exit(0);
      void this_windowClosed(WindowEvent e) {
        System.exit(0);
      void this_windowClosing(WindowEvent e) {
    System.exit(0);
      void clear_btn_actionPerformed(ActionEvent e) {
      log.setText("");
    class FileServer_stop_btn_actionAdapter implements java.awt.event.ActionListener {
      FileServer adaptee;
      FileServer_stop_btn_actionAdapter(FileServer adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.stop_btn_actionPerformed(e);
    class FileServer_this_windowAdapter extends java.awt.event.WindowAdapter {
      FileServer adaptee;
      FileServer_this_windowAdapter(FileServer adaptee) {
        this.adaptee = adaptee;
      public void windowClosing(WindowEvent e) {
        adaptee.this_windowClosing(e);
    class FileServer_clear_btn_actionAdapter implements java.awt.event.ActionListener {
      FileServer adaptee;
      FileServer_clear_btn_actionAdapter(FileServer adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.clear_btn_actionPerformed(e);
    //**********************CLIENT************************************
    package servermanager;
    import java.net.*;
    import java.util.*;
    import java.io.*;
    public class FileClient {
      Socket socket;
      DataOutputStream dataout;
      public   void SetSocket(String dir,String filename) {
        try {
          socket = new Socket("localhost", 9898);
          dataout = new DataOutputStream(socket.getOutputStream());
            //sending Username & DIR name
            dataout.writeUTF(dir);
            //Sending Filename
            dataout.writeUTF(filename);
            dataout.flush();
            File f = new File("Accounts//"+dir+"//"+filename);
            byte data[]=new byte[4096];  //40k
            long filelength=f.length();
            String lenbuf = String.valueOf(filelength);
             byte lenz[] = lenbuf.getBytes(); //file length in bytes
               int lenzLen = lenz.length;
            FileInputStream fis = new FileInputStream(f);
            dataout.write(lenzLen);  //sending length in integer
            dataout.flush();
            System.out.println(lenzLen+"--------First Thing Sent length of byte array");
            dataout.write(lenz);      //sendinf byte  Array length
            dataout.flush();
              System.out.println(lenz+"--------Second Thing Sent bytes");
            int loop=0;
              while(loop!=-1){
                loop=fis.read(data);
                dataout.write(data);
                dataout.flush();
              socket.close();
        catch (UnknownHostException e) {
          System.out.println("Unknown host:");
          System.exit(1);
        catch (IOException e) {
          System.out.println("No I/O   " + e.getMessage());
          System.exit(1);
        catch (Exception e){
          e.printStackTrace();
      public static void main(String args[])  {
        FileClient serv = new FileClient();
        FileBean file=new FileBean();
        String wavfiles []=null;
        String dirs []=  file.getDirsForSocket("Accounts//");
        for(int i=0;i<dirs.length;i++){
        wavfiles= file.getWavfiles("Accounts//"+dirs[i]+"//");
         //if (wavfiles.length==0)
              for (int j=0;j<wavfiles.length;j++){
                  serv.SetSocket(dirs,wavfiles[j]);

  • Is anyone having problems sending files from SendNow now that they've used Send?

    I sent a couple files in Send and now I cannot send files in SendNow.  It tells me to check my internet connection and that it cannot send the files.  I've reset the internet connection and it still does not work.  I even tried send a file through Send and it worked fine, but when I went back into SendNow I got the same message. Are other people having issues with this? Any suggestions?

    It is very strange because I've always used Google Chrome to use SendNow
    and I've never had a problem until this morning after trying Send.  I went
    it and tried it in Firefox and it worked fine, but still doesn't in Chrome.
    Not sure what happened because I used Send in Chrome and it worked fine.
    Thank You,
    Roxanne Schutz
    Gatehouse Media, Inc. NE Holdings, Inc.
    Heartland Classifieds- Maverick Media, Inc.
    Penny Press 1, Penny Press 4, News-Press,
    Syracuse Journal-Democrat, Hamburg Reporter
    P.O. Box "O"
    Syracuse, NE  68446
    1-877-269-3358
    [email protected] <[email protected]>
    This message may contain confidential and/or privileged information.  If
    you are not the intended recipient or authorized to receive this for the
    intended recipient, you must not use, copy, disclose or take any action
    based on this message or any information herein.  If you have received this
    message in error, please advise the sender immediately by sending a reply
    e-mail and delete this message.  Thank you for your cooperation.

  • How to send packet using tcp socket ?

    hi ,
    i want to using tcp socket to send data in ipv6 environment. but why the data transfer is less than ipv4 environment?
    socket = new Socket("2001:0238:0600::2", 1234);am i wrong ?

    bobby92 wrote:
    why the data transfer is less than ipv4 environment?What do you mean?
    >
    socket = new Socket("2001:0238:0600::2", 1234);am i wrong ?No idea, since I've no idea what you're asking.

  • File Content Conversion Problem: Sender File Adapter

    Hi All,
    In Sender File Adapter, how to spilt the single line into different lines using + as a separator. Plz see below my source file.
    #SMESS=IV01:672633SAP:676968:::NL51:02:11+
    COPS=678713:676968:070416:IV01'3:11IVFR=678713:PDA and'IND 2'9206 AD'Dtn'INIVDA=070416IVNR=6264008195:676968add1
    #EMESS=0+
    In above txt file there are 3 lines.
    1st line starts with #SMESS
    2nd line starts with COPS 
    3rd line starts with #EMESS.
    In 2nd line, if u observe there are 3 lines separating by +. My task is, I have to spilt the 2nd line into 3 lines using + separator.
    I already used the xx.endSeparator as '+' to spilt the line but it is not working....
    Could anyone help me how to do this. This is very urgent
    Thnx,
    Kumar.

    Hi Shankar,
    1) My Expected XML Structure:
      <?xml version="1.0" encoding="utf-8" ?>
    - <ns:MT_IV01 xmlns:ns="http://ms.com/dev/ms">
    - <Recordset>
    - <DT_SMESS>
      <D_9901>IV01</D_9901>
      <D_9902>672633SAP</D_9902>
      <D_9903>676968</D_9903>
      <D_9904 />
      <D_9905 />
      <D_9906>NL51</D_9906>
      <D_9907>02</D_9907>
      <D_9908>11</D_9908>
      </DT_SMESS>
    - <DT_COPS_2>
      <D_C022>678713</D_C022>
      <D_C023>676968</D_C023>
      <D_C008>070416</D_C008>
      <D_C111>IV01'3</D_C111>
      <D_H559>11</D_H559>
      </DT_COPS_2>
    - <DT_IVFR_2>
      <D_C024>678714</D_C024>
      <D_D333>PDA and'IND 2'9206 AD'Dtn'IN+</D_D333>
      </DT_IVFR_2>
    - <DT_IVDA_2>
      <D_D365>070416</D_D365>
      </DT_IVDA_2>
    - <DT_IVNR_2>
      <D_D189>6264008195</D_D189>
      <D_H364>676968add1</D_H364>
      </DT_IVNR_2>
    - <DT_EMESS>
      <D_D9901_1>0</D_D9901_1>
      </DT_EMESS>
      </Recordset>
      </ns:MT_IV01>
    2) I am not getting any error even if I use key Fields or Not becoz in the RecordSet Structure I mentioned DataType, 1 instead of DataType, *.
    3) FCC Parameters:
    Document Name: MT_IV01
    Document Namespace: http://ms.com/dev/ms
    Recordset Structure: DT_SMESS,1,DT_COPS_2,1,DT_IVFR_2,1,DT_IVDA_2,1,DT_IVNR_2,1,DT_EMESS,1
    Recordset Sequence: Ascending
    Key Field-type : String (Case-sensitive)
    4) Error:
    Conversion of file content to XML failed at position 0: java.lang.Exception: ERROR converting document line no. 2 according to structure 'DT_COPS_2':java.lang.Exception: ERROR in configuration: more elements in file csv structure than field names specified!

  • Sending files with Mulicast sockets

    Hi,
    I'm trying to write a multicast sender/receiver applications for windows.
    The problem I'm having is that the receiver create bigger file than the source (double or bigger).
    Chcking with debugger the sender does not send the file more than one time & file length is measured correctly.
    What am I doing wrong? Is Java multicast reliable on windows?
    Please see below my code and comment.
    Thanks,
    Alonex
    /* Multicast sender */
    import java.io.*;
    import java.net.*;
    public class Outcoming extends Thread
         int port;     //4446     
         String multicastServer="230.0.0.1";     
         MulticastSocket out;
         byte[] outBuffer;
         String username;
         String msg;
         DatagramPacket dp;
         InetAddress multicastserverIP;
         static boolean done = false;
         public Outcoming() throws IOException, UnknownHostException
              port=4446;
              username="kostas";
              out=new MulticastSocket(4446);
              out.setTimeToLive(10);
    //          out.joinGroup(InetAddress.getByName(multicastServer));          
         }/////////////////////Outcoming     
         public void run()
              while (!done)
              try {
                   multicastserverIP=InetAddress.getByName("230.0.0.1");
              catch (UnknownHostException e)     
                   System.out.println("Cannot resolve ip address");
              try {
                   System.out.println("ttl"+out.getTimeToLive());
                   out.joinGroup(multicastserverIP);
              catch (IOException e)
                   System.out.println("Failed to join group");
              boolean readMore=true;
              String line="";     
              createAndSendPacket(line);
              while (readMore)
                   System.out.print(">"); 
                   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                   try     {
                        line=br.readLine().trim();
                   catch (IOException e)     {
                        e.printStackTrace();
                   if (line.equalsIgnoreCase("quit"))     
                        readMore=false;
                   createAndSendPacket(line);
    //     }/////////////////////run
    //     Returns the contents of the file in a byte array.
          public static byte[] getBytesFromFile(File file) throws IOException {
               InputStream is = new FileInputStream(file);
               // Get the size of the file
               long length = file.length();
               // You cannot create an array using a long type.
               // It needs to be an int type.
               // Before converting to an int type, check
               // to ensure that file is not larger than Integer.MAX_VALUE.
               if (length > Integer.MAX_VALUE) {
                    // File is too large
               // Create the byte array to hold the data
               byte[] bytes = new byte[(int)length];
               // Read in the bytes
               int offset = 0;
               int numRead = 0;
               while (offset < bytes.length
                        && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
                    offset += numRead;
               // Ensure all the bytes have been read in
               if (offset < bytes.length) {
                    throw new IOException("Could not completely read file "+file.getName());
               // Close the input stream and return bytes
               is.close();
               return bytes;
         private void createAndSendPacket(String msg)
              int i,j=0,s=1;
             byte[] buf1=new byte[64000];
              try     {
                   msg=username+"#!#"+msg;
    //               byte[] buf=msg.getBytes();
                   File fileTest = new File("c:\\test.exe");
                   byte[] buf=getBytesFromFile(fileTest);
                   int size = 64000;
                   while (j<buf.length)
                        if ((s*64000)>buf.length)
                             size = buf.length-((s-1)*64000);
                             buf1 = new byte[size];
                             done=true;
                   for (i=0;i<size;i++,j++) //buf.length;i++)
                        if (j==1822845)
                             System.out.println("here");
                        buf1=buf[j];
                   if (i==size)
                        dp=new DatagramPacket(buf1, buf1.length,multicastserverIP , port);
                        out.send(dp);
                        try
                        Thread.sleep(3000);
                        catch (InterruptedException ie){}
                        System.err.println("Packet sent");
                        s++;
              catch (UnknownHostException e)
                   System.out.println("createAndSendPacket: UnknownHostException");
              catch (IOException e)
                   System.out.println("createAndSendPacket: IOException "+e.toString());
         }/////////////////////createAndSendPacket
         public static void main(String[] args) throws IOException, UnknownHostException
              new Outcoming().run();
    /* Multicast Receiver */
    import java.io.*;
    import java.net.*;
    public class Incoming extends Thread
         int port;     //4446     
         String multicastServer="230.0.0.1";
         MulticastSocket in;
         byte[] inBuffer;
         String username;
         String msg;
         InetAddress multicastserverIP;
         public Incoming()
              port=4446;
              msg="";
              try {
                   in=new MulticastSocket(port);
                   in.setTimeToLive(10);
              catch (IOException e)
                   System.out.println("Failed to create multicast socket");
         public void run()
              try {
                   multicastserverIP=InetAddress.getByName(multicastServer);
              catch (UnknownHostException e)     
              try {
                   in.joinGroup(multicastserverIP);
              catch (IOException e)
                   System.out.println("Failed to join group");
              while (!msg.trim().equalsIgnoreCase("quit"))
                   readSocket();
                   writeFromBuffer();
         private void readSocket()
              inBuffer=new byte[64000];
              DatagramPacket rcv=new DatagramPacket(inBuffer, inBuffer.length, multicastserverIP , port);
              try     {
                   in.receive(rcv);
              catch(IOException e)
                   System.err.println("Failed to receive incoming message");
         private void writeFromBuffer()
              try
              FileOutputStream fos = new FileOutputStream(new File("c:\\temp.exe"),true);
              fos.write(inBuffer);
              fos.close();
              catch(IOException ie){};
         public static void main(String[] args) throws IOException, UnknownHostException
              new Incoming().run();

    (a) Multicast isn't reliable on any platform. Datagrams may be lost, duplicated, or delivered out of order, and datagrams greater than 534 bytes are unlikely to get though routers at all even if multicasts do.
    (b) Why are you joining the multicast group every time around the loop?
    (c) You are ignoring the actual length of the received datagram, just assuming it is 64000.
    (d) In fact you are also ignoring exceptions when reading and still writing out 64000 bytes even if nothing was read at all.
    All in all you need to rethink this.

  • Problems sending files to new iMac

    I have tried to send folders from our MacBook to our new iMac (out of the box 2 days ago!), and keep on getting a 'Device does not have the necessary services' message. Just in case it was the MacBook with the problem I have tried sending media files from my phone to the iMac and keep on getting 'failed' messages. I tried to send a file from the iMac to the MacBook and this worked, so it's in the receiving, rather than the sending. What can I do? Thanks

    Have you enabled Bluetooth Sharing in the System Preferences? Go to Sys Prefs/Sharing and check the box to allow Bluetooth sharing in the Sharing services list on the left of the pane. You will then be offered a number of things to configure when using this service on the right of the pane.
    Dah•veed

  • Problem sending files

    Hello!
    I'm trying to send a music file that I made to a friend of mine. I am able to send songs to one of my friends no problem, but for some reason I can't seem to send it with any others. I have File Sharing on and my Firewall allows it. I'm assuming it's his computer that is causing problems? (He has a MacBook). I suggested for him to allow file sharing and check his firewall, but no success. Any other ideas?

    Can you send him any other sort of file ?
    9:30 PM Friday; January 11, 2008

  • Why I cannot send byte throught a socket?

    Hi guys!
    I've a problem: I want to send some bytes from a client to a server (very simple.....).
    I'm using this piece of code for the client:
    BufferedOutputStream bos=new BufferedOutputStream(s.getOutputStream());
    int lunghezzadati=dati.length;
    bos.write(lunghezzadati);
    bos.flush();
    bos.write(dati,0,lunghezzadati);
    bos.flush();
    System.out.println("Data sended to the server:"+dati);
    (It send first a int that is the lenght of the byte array, so it send the byte array)
    This is a piece of the code of the server
    BufferedInputStream bis=new BufferedInputStream(sock.getInputStream());
    int lunghezzaricevuta=bis.read();
    byte[] datiricevuti=new byte[lunghezzaricevuta];
    bis.read(datiricevuti,0,lunghezzaricevuta);
    System.out.println("Data form the client:"+datiricevuti);
    When I run the client and the server the data sended and the data receveid are not equal!!!
    Why?
    There is someone the can help me? This is for my thesis......, and I must terminate the program before tonight!!!!
    P.S. Sorry for my English...

    Try swapping your buffered streams with data streams. When you write an int to a BufferedOutputStream, you are actually writing a single byte value. This should not correspond to "length" of expected transmission (someone may correct my if I am wrong, but I believe you have to flip the high bits to get the byte to behave the way you are attempting).
    // Sender/Client
    byte[] data = "Hello world".getBytes();
    DataOutputStream dataOut = new DataOutputStream(out); // out is someOutputStream, presumably a socket's
    dataOut.writeInt(data.length);
    dataOut.write(data, 0, data.length);
    dataOut.flush();
    dataOut.close(); // not required if you are going to recycle the socket
    // Receiver/Server
    DataInputStream dataIn = new DataInputStream(in); // in is some InputStream, presumably a socket's
    int length = dataIn.readInt();
    byte[] buffer = new byte[length];
    if (length >= 0) {
    dataIn.read(buffer, 0, length);
    System.err.println("Received " + length + " bytes of data: " + new String(buffer));
    dataIn.close(); // not required if you are going to recycle the socket
    - Saish
    "My karma ran over your dogma." - Anon

  • RE: Problems sending files due to encryption..help

    I am trying to attach a resume to a posting from a job site but I keep getting an error that says the file cannot be used due to encryption.  I never had this issue with comcast, can anyne help me with either changing my setting or tell me what I am doing wrong?  Thanks!!

    hoopfan1 wrote:
    I am trying to attach a resume to a posting from a job site but I keep getting an error that says the file cannot be used due to encryption.  I never had this issue with comcast, can anyne help me with either changing my setting or tell me what I am doing wrong?  Thanks!!
    What mail client are you using? I have had issues with different programs sending a message encrypted without realizing it. I hate Lotus Notes, and don't know if I will ever get used to it. Where are you getting the error? Error with Mail Client or receiving end telling you it can not open the file?

  • Problem sending files from Pages via email

    I am using a Yahoo business mail account. All other emails send just fine using Mail. When I try and send a document out of Pages, it brings up the compose new mail fine and it makes the "whoosh" noise indicating that it's been sent. The recipient doesn't receive it, and it doesn't show up in my "sent items" folder. I tried to send using both wifi and 3G for interest's sake, and neither works.
    I'm not sure what to try to fix this, or if it's a limitation of the SMTP server, or what. Any help would be greatly appreciated - my iPad Pages is gimped without the ability to share documents by email...

    Welcome to Apple Discussions
    iWork documents are packages, a special type of folder. Even though with iWork '09 & iWork for iPad they no longer appear as packages, they still are. On a Mac right-click on the file & look for show package contents. If that option is not there it is a "flat-file" but it can still be unzipped.
    Anyone with Stuffit Expander installed with default settings & who saves Pages files to the Desktop will find folders instead of just the document. This is because Stuffit "sees" the file for what it really is, a package. You can check for yourself by changing the extension from .pages to .zip & unzip the file. You can't e-mail a folder which is why many mail clients balk. Apple Mail will automatically zip a folder, other e-mail clients don't, especially web-based e-mail. I think you may be mailing as a Pages document rather than Word or PDF.

  • Problem sending file to co-worker

    Hi everybody. I'm a casual ID user -- pardon me if I'm making a bonehead mistake or leaving out any key info from this message.
    I'm working on a MacBook Pro, using ID CS3 5.0. on OS X 10.5.8.
    I created a rough draft of a playbill, saved it as a standard ID document (indd) and emailed it to a graphic designer to touch up. She couldn't open it. We thought that was because she was using CS2. So she upgraded to CS3. But still no luck. Nor can she open an inx version I sent.
    I just emailed her asking what error message she's getting. I think she said on the phone that it was something generic along the lines of 'ID can't open this file."
    Any idea what's going on and how we can fix it? Are there any formats besides ins we could try?

    Emailing loose files can result in damage to the files. This has happened to me in the past. Some email services compress files that aren't already compressed.
    Collect the files (you can use the Package for Print to do this) to a folder on your desktop.
    You can deselect the options for fonts an/or links if desired) to help reduce the size.
    Right Click (or Command Click) on the resulting folder and select the "Compress (folder name) option from the contextual menu.
    This will create a ZIP archive of the folder.
    Email that instead of the loose files.
    Or, you can use the YouSendIt to deliver your files if they are too large for your email service (doesn't sound like it, though)
    Hope that helps
    -mt

Maybe you are looking for