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.

Similar Messages

  • I'm unable to send and receive email through Apple Mail 4.  I've checked my settings on Preferences, and my password to Gmail is up to date for syncing with IMAP, but it still won't connect.  Suggestions?

    I'm unable to send and receive email through Apple Mail 4.  I've checked my settings on Preferences, and my password to Gmail is up to date for syncing with IMAP, but it still won't connect.  Suggestions?

    I think it's trying to open it in a gMail eMail & is losing your gMail password that it needs log into gMail, but not 100% positive.
    Have you tried Right clicking or Control+click on the eMail link & choose Copy? Works on some, not others.

  • Send and receive files between unix machines

    Hi friends,
    I have to send and receive files from one unix machine to another unix machine. In my first unix machine I have tomcat webserver. Using a JSP I have to send and receive files from this machine to another machine. The destination machine contain some BAAN implementation, which take the files I send as input .
    Can you send me a java program to solve this problem.

    Hi friends,
    I am getting a problem in my application. I will state the complete problem in detail. I have to transfer 3 files from one NT machine to unix machine some where kept in net work, I used an ftp in 'Process p = getRunTime().exec("ftp -i -s:ftp.txt")'. In ftp.txt file I have given the necessary things for ftp to unix machine. The files are transfering into the unix box. When I to the process for the 2nd time I have to check whether the file are exists in the unix box, then only transfer the files. Now, again I am doing ftp bring the files from the unix box to NT machines using 'Process p = getRunTime().exec("ftp -i -s:ftp1.txt")' where ftp1 contains all the necessary things for ftp to unix machine . Now I am checking for the files available in the NT machine using boolean=(new File(filename)).exists(), Fine out of 3 files, 2 file shows the return type as 'true' and one file is showing 'false', even the same happens if I delete the 3 files after checking, out of 3 files, 2 file shows the return type as 'true' and one file is showing 'false'. I went to the folder where I am bring files from and removing the files manually, one file is showing share violation, one process is using the file . I am unable to resolve this problem, will this code what I write is acceptable if not suggest any other code. I have sending all the snippets of the programs. I am doing this in the development environment like this. My production environment is totally both are unix machines.
    1. ftp to transfer files.(tranfer.txt)called in java code down
    open 172.16.30.6
    informix
    informix
    bin
    has
    cd /tmp
    put d:/dathu/CSV/bssfa932.txt
    put d:/dathu/CSV/bssfa933.txt
    put d:/dathu/CSV/bssfa936.txt
    bye
    2. ftp to get the files(get.txt)used in java code down
    open 172.16.30.6
    informix
    informix
    bin
    has
    cd /tmp
    lcd d:/dathu/hold
    get bssfa932.txt
    get bssfa933.txt
    get bssfa936.txt
    bye
    3. java code snippet to getfiles
    Process p = Runtime.getRuntime().exec("ftp -i -s:get.txt");
    4. java code to check the files exist
    boolean filestatus=moCreatFlatFilerobj.isFileExists();
    public boolean isFileExists(){
    boolean isfileexisting=false;
    boolean blnordhead = (new File(file1 with path)).exists();
    boolean blnordlines = (new File(file2 with path)).exists();
    boolean blnaccount = (new File(file3 with path)).exists();
    if(blnordhead && blnordlines && blnaccount){
    isfileexisting=true;
    return isfileexisting;
    5. java code to delete files
    public void deleteFiles(){
    boolean header= (new File(file1 with path)).delete();
    boolean line =(new File(file2 with path)).delete();
    boolean account=(new File(file3 with path)).delete();
    6. java code to tranfer files.
    p = Runtime.getRuntime().exec("ftp -i -s:transfer.txt");

  • Sending and receiving Signal through Internet connection

    Hello,
    I want to send data that is a continuous generated signal through internet.
    I want to transmit this signal live through internet technology.
    I don't have any background of web development
    Can anyone suggest me how could I send and receive data using internet.
    Regards

    Hello,
    I have made a basic VI using Network Stream, it send Random Number generator which i want to plot on a waveform chart on the other side.
    But when i run the VI on continuous mode it gives an error as End point broken on the client side.
    Kindly guide where i am lagging.
    Regards
    Attachments:
    streams.vi ‏14 KB

  • How can i send and receive messages through CAN

    Hi,
    how can i send and receive messages using Vector CAN CARDXL

    As mentioned in this forum post, if you have a dll, this can easily be called from LabVIEW or CVI.
    I also went to the vector website and it does look like they have LabVIEW drivers available for download.
    Peter Flores
    Applications Engineer

  • Send and Receive Files

    I found that on my desktop computer I cannot send or receive any files (pictures, documents, etc). However if I log into skype on my Android phone i can receive and send files. Why is this happening and how can I fix it?
    I'm on Skype Version 7.2.59.103
    Solved!
    Go to Solution.

    Try to reset all Internet Explorer settings:
    http://support.microsoft.com/kb/923737
    Next reset LAN settings:
    Open Internet Explorer. Go to Tools -> Internet Options -> Connections -> LAN settings. Make sure that the only option selected is “Automatically detect settings”.
    Next clear all Temporary Internet Files:
    Open Internet Explorer -> Tools -> Internet Options -> General. In the section “Browsing history” press the “Settings” button and in the next window the “View files” button. Delete all files from the Temporary Internet Files folder.
    Reboot your computer and test now what happens when you open this link in your Internet Explorer.
    https://api.asm.skype.com/s/i

  • Same Sender and Receiver File Name. Pls advice urgent

    Hi All,
    My sender file name is auto generated number so
    it is dynamic in nature.
    ex. "abc1.txt"
         "abc2.txt"
    Now In my Sender File Adapter I cannot give
    File Name hard coded as my sender file name is auto generated number.
    Also I want same file name received at receving end.
    File Sender --   "abc1.txt"
    File Receiver -- "abc1.txt"
    File Sender --   "abc2.txt"
    File Receiver -- "abc2.txt"
    Pls advice.
    Regards

    Hi Rider,
    All your sender files have .txt extension but the name is not constant(dynamic in nature).Than in this case to pick ur file u can use the *.txt as ur sender file name.Than all the files with .txt extension in the source folder specified would be picked.
    Than u can proceed in the same way given in this blog
    /people/michal.krawczyk2/blog/2005/11/10/xi-the-same-filename-from-a-sender-to-a-receiver-file-adapter--sp14
    Please let me know if u need any information
    Thanks,
    Bhargav
    Note:Award points if found useful

  • Sender and receiver File Adapter

    Hi ,
    Sender File
    12345566767
    fjwehifh
    09782345sdfgsjghjghhh
    83475 dsf888234  dsfsdf wefrwr
    Question1 : I need to Treat the Complete Message as a Field
    Eg :  MY Source Structure
    Recordset
       record
           Field1 0..1
    I need to read complete file as one field, How can i achive it
    Thanks in advace

    Hi all,
    As my understanding, requirement is that the source file is haphazard and the data type of source has only one field, we should read all the content from the file and convert to the DT which has only one field. and we should map the flat not xml content to target.
    correct if i am wrong,
    anyone has a suggestion for this?
    Regards,
    Kevin Song

  • How can I use my mobile number to send and receive sms through Messages Mac?

    How can I do this? I am in the Philippines. Thanks.

    You can only use your phone number with iMessage if you have got the iPhone. If you have got it, on the Mac, open Messages, go to Messages menu (on the menu bar) > Preferences > Accounts, and tick the phone number

  • How can I be sure iMessage is sending and receiving via WiFi and not using my text message allotment?

    My daughter has a new iPad Touch and I have a 3GS with 5.0.1. She wants to send and receive a million messages from me each day day with iMessage. Right now, I have Settings>Messages>Send As SMS - OFF. With this current setting, can I be assured I am using the WiFi only and not burning my SMS allotment from ATT? Am I safe to restore Send As SMS setting to ON? In other words, will the default method of transmission of text messages be through the internet, when that service is available?
    Without waiting for a $1000 bill from ATT for text messages, can I ensure I'm sending and receiving iMessages through the WiFi only?

    Well, I just noticed that a shaded iMessage appears in the enter text window when sending to her iPod Touch and my messages appear in a blue balloon, with her replies are in gray balloons. When sending to someone with another kind of phone, the text entry window says "Text Message" and my balloons are green. I guess this is an indication that the iMessage system is working and I'm not blowing through my SMS allotment from ATT.
    With these indications, can I be sure I'm messaging through the iMessage system, or the carrier's SMS service?

  • TCODES FOR SENDINGIG AND RECEIVING DATA THROUGH ALE

    Hi,
    All,
    Message type I can find for the following :
    Equipment master: EQUIPMENT_CREATE
    Work centre: WORKC2, WORKC3 or WORKC4
    Functional location: FUNC_LOC_CREATE
    but i did'nt  find  a transaction code for sending and receiving data through ALE.
    For example:  Send material    T.code BD10,
                         Receive material T.code BD11.
    Please give the solution.
    Regards.

    can Tx BD21 is of any help

  • Java codes and apis to send and receive SMS using a GSM modem(iTegno3000)

    Could any one please send me the codes and apis that can be use to send and receive SMS through iTegno3000 modem(GSM modem).I am a srilankan undergraduate.I am looking forward to hearing from you soon.

    hi i am also have the same doubt ..did u get soluation for this means can u reply to me

  • Messages will not send or receive files.

    My messages app picks and chooses when it will send and receive files. Usually they are images or videos but also some Pages documents. Bringing up the file transfer window shows the spiraling download bar for receiving files and sending files will say "sent 0 kb of ____" and not move. Is there anything I can check to

    Same here ???????

  • Code to automatically sms send and receive by sql server

    I want you to tell me the necessary code in vb and sql to automatically send and receive sms from sql database.i know only that i have to create one table for it in the database.please anybody who knows post the code for me.

    Hi mintesnot h.benti,
    According to your description, since the issue regards VB code, as other post, you need to post the related problem on Visual Basic forum at
    http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=vbgeneral. It is appropriate and more experts will assist you.
    In addition, if you want to use a SQL Server database, and it makes SMS sending and receiving possible through database tables in your VB.NET application. You may need to use the 3<sup>rd</sup> tools, such as OZEKI NG SMS Gateway or others.
    http://www.ozekisms.com/php-sms-api-asp-sms-A/index.php?owpn=586&sms_gateway=sms_VB.NET_database_sms_example_guide
    Note: Microsoft is providing this information as a convenience to you. Microsoft does not control these sites and has not tested any software or information found on these sites; therefore, Microsoft cannot make any representations regarding the quality,
    safety, or suitability of any software or information found there. There are inherent dangers in the use of any software found on the Internet, and please be cautious and ensure you have completely understood the risk before retrieving any software from the
    Internet.
    Regards,
    Sofiya Li
    Sofiya Li
    TechNet Community Support

  • HT201415 cannot send and receive imessages from phone number. Will not allow number to be ticked

    Cannot send and received imessages through phone numer.  Will not allow me to tick number

    Turn off iMessage and turn it back on.

Maybe you are looking for