Problem in sending file thru sockets

Hello
i am sending a file thru sockets....the file reaches the server but there is loss of file contents. i do not recieve the entire file. whats wrong?
my Server code
//package socket_try ;
// SimpleServer.java: a simple server program
import java.net.*;
import java.io.*;
import javax.comm.*;
import java.util.*;
public class Server
public static final int BUFFER_SIZE = 1024 * 50;
static CommPortIdentifier portId;
static Enumeration portList;
SerialPort serialPort;
Thread readThread;
public static void main(String[] ar)
byte[] buffer;
buffer = new byte[BUFFER_SIZE];
int port = 6666; // just a random port. make sure you enter something between 1025 and 65535.
boolean portFound;
try
ServerSocket ss = new ServerSocket(port); // create a server socket and bind it to the above port number.
System.out.println("Waiting for a client...");
Socket socket = ss.accept(); // make the server listen for a connection, and let you know when it gets one.
System.out.println("Got a client :) ... Finally, someone saw me through all the cover!");
System.out.println();
BufferedInputStream bin = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("c:\\SMS.txt"));
int in;
try
int len = 0;
          while ((len = bin.read(buffer)) > 0) {
               bos.write(buffer, 0, len);
               System.out.print("#");
          bin.close();
          bos.flush();
          bos.close();
          socket.close();
ss.close();
catch(Exception x)
x.printStackTrace();
catch(Exception e)
System.out.println("Exception : "+e);
my client code
import java.net.*;
import java.io.*;
public class Client
public static final int BUFFER_SIZE = 1024 * 50;
public static void main(String[] ar)
int serverPort = 6666; // make sure you give the port number on which the server is listening.
String address = "192.168.1.3"; // this is the IP address of the server program's computer. // the address given here means "the same computer
as the client".
int in=0;
byte[] byteArray;
byte[] buffer;
buffer = new byte[BUFFER_SIZE];
try
InetAddress ipAddress = InetAddress.getByName(address); // create an object that represents the above IP address.
System.out.println("Any of you heard of a socket with IP address " + address + " and port " + serverPort + "?");
Socket socket = new Socket(ipAddress, serverPort); // create a socket with the server's IP address and server's port.
System.out.println("Yes! I just got hold of the program.");
// Get the input and output streams of the socket, so that you can receive and send data to the client.
// Just converting them to different streams, so that string handling becomes easier.
BufferedInputStream bis;
BufferedOutputStream bos;
bis = new BufferedInputStream(new FileInputStream("c:\\send.txt"));
bos = new BufferedOutputStream(socket.getOutputStream());
byte[] receivedData;
int len = 0;
while ((len = bis.read(buffer)) > 0)
bos.write(buffer, 0, len);
System.out.print("#");
     for(int y =0 ; y < buffer.length ; y++)
char s =(char) buffer[y];
System.out.println("character:"+s);
bis.close();
bos.flush();
bos.close();
socket.close();
System.out.println("\nDone!");
catch(Exception x)
x.printStackTrace();
} /* end of main */
}/* end of class */
what is wrong can please anyone tell me??????

As I don't know how long a record is, that's not a very useful answer. How many bytes are you expecting and how many do you actually get?

Similar Messages

  • Problem with Sending files over Sockets

    Hi. I have a problem when I try to send files over sockets. When I send text files it works well but when I try to send .jpg or other kind of files it doesn't work well because some characters are wrong, I hope you can help me.
    Here is my code:
    //Sender code
    import java.io.*;
    import java.net.*;
    class Servidor{
         Servidor(){
              try{
                   String arch="art.jpg";
                   ServerSocket serv=new ServerSocket(125);
                   Socket socket=serv.accept();
                   System.out.println("Conectado");
                   int c;
                   BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                   FileInputStream fis=new FileInputStream(arch);
                   File f=new File(arch);
                   bw.write(""+f.length());
                   bw.newLine();
                   bw.flush();
                   System.out.println("Escribiendo");
                   while((c=fis.read())!=-1){
                        bw.write(c);
                   bw.flush();
                   fis.close();
                   System.out.println("Terminado");
                   while(true){
              }catch(Exception e){
                   System.out.println(e);
         public static void main(String arg[]){
              new Servidor();
    //Client code
    import java.io.*;
    import java.net.*;
    class Cliente{
         Cliente(){
              try{
                   Socket socket=new Socket("localhost",125);
                   System.out.println("Conectado");
                   BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                   long tam=Long.parseLong(br.readLine());
                   long act=0;
                   FileOutputStream fos=new FileOutputStream("resp.jpg");
                   System.out.println("Recibiendo: "+tam);
                   while(act<tam){
                        fos.write(br.read());
                        act++;
                   System.out.println("Terminado: "+act+" / "+tam);
                   fos.close();
              }catch(Exception e){
                   System.out.println(e);
         public static void main(String arg[]){
              new Cliente();
    }

    I don't think you want BufferedReader and OutputStreamWriter, you want ByteArrayOutputStream and ByteArrayInputStream . The problem is that you are sending jpegs (binary data) as text.

  • How to send the directory listing and file thru socket?

    I need to know where can i learn the directory listing and sending file thru socket. I m going to develop a simple FTP server/client application..Pls help, thnx!

    Above where you're reading this, and to the right of your screen is a magical little box that, when you type in something like "ftp server tutorial" will take you to a page with some hyperlinks you can click. That little box is used for searching the forum. You can tell this because right above the box, it says "Search Forum". You even have the option of using your <enter> key or the "go" button to begin the searching, once you've typed in your criteria, of course. Pretty handy, huh? Well, I won't keep you any longer. Go ahead, give it a shot. It doesn't hurt, and you might actually get some valuable results for the minimum amount of effort you're apparently willing to exert.

  • I'm having problems receiving/sending emails thru Outlook.

    I switched internet connection from AT&T to Comcast and I'm still utilized several AT&T email address's for free. I'm having problems receiving/sending emails thru Outlook.  Could the problem be due to using their free emails with no support.
    Do I have to go thru yahoo to read/send emails?

    Change the ISP would not effect the email connection generally. (Only when ISP disable your mailbox which they could control directly.)
    I suppose that your Outlook still store/cache the AT&T messages, try to export them as PST data file for backup.
    Setup the new Yahoo in your current Outlook first and then import that backup.pst to continue to use.
    http://support.microsoft.com/kb/287070/en-us
    Thanks
    Tony Chen
    TechNet Community Support

  • Send files thru email

    hey all
    is it possible to send files thru email using a java program??? i tried using Runtime..... and executing outlook...but i could not figure out how to give filename and reciever's name at the command prompt...can anybody help me in this???
    thanx in advance
    bharthi

    This is a good tutorial for javamail:
    http://developer.java.sun.com/developer/onlineTraining/JavaMail/
    The part about sending attachments is:
    http://developer.java.sun.com/developer/onlineTraining/JavaMail/contents.html#SendingAttachments

  • Problem in sending mail thru SAP.

    Hi All
    I have typical problem in sending Purchase order thru mail to vendor.
    We are sending Purchase Order to our vendor thru mail and copy of purchase order as attachment in pdf file.
    I am sending Purchase Order number 45XXXX01, vendor is getting something else say 45XXXX03. But when I checked the same in outbox in SAP business workplace then it is found correct i.e. Purchase Order number 45XXXX01 but when vendor open his attachment then he is found Purchase Order number 45XXXX03.
    Following FMu2019s are used in y-program to send mail.
    CONVERT_OTF u2013 To convert into pdf.
    SO_DOCUMENT_SEND_API1 u2013 To send mail.
    I do not understand why it is happening.
    Kindly suggest something to overcome this.
    Regards,
    Rajesh Vasudeva

    Hey do as follow
    1 > When you send the mail , after running ur program , you furst open the sent data from SOST or SCOTT etc. and see is it a correct data.
    2 > Try sending the mail to urself , also try to mention ur id along with vendors Id and see what do u get also same time check what r u sending.
    Hopefully it will give you some idea.
    Regards,
    Uma Dave

  • Problem in Sender File Adapter using FCC with Variable structure

    Hi Experts,
    Hi Experts,
    I have facing an issues while using FCC in Sender File adapter. Below are the configs for the same:-
    Recordset structure required is ==HEADER,1,DATA,*,TRAILER,1
    Recordset per message == *
    Key Field Name == Key
    (Sorry i dont know how to insert screen shot here..pls tell me how can i insert screen shots here on sdn)
    HEADER.fieldSeparator           ,
    HEADER.endSeparator           u2018nlu2019
    HEADER.fieldNames               Key,x,y,zu2026
    HEADER.keyFieldValue          1
    HEADER.keyFieldInStructure      ignore
    HEADER.fieldContentFormatting     trim
    HEADER.additionalLastFields     ignore
    HEADER.missingLastFields     ignore
    DATA.fieldSeparator
    DATA.endSeparator
    DATA.fieldNames
    DATA.keyFieldValue
    DATA.keyFieldInStructure
    DATA.fieldContentFormatting
    DATA.additionalLastFields
    DATA.missingLastFields
    Using same variables for Trailer record as well.
    Source CSV file which i am picking:-
    ADSE ,RASD,replan  Contact ,2  0080509 0 8:43:25   ,        
    EMPL ,0011111,  S Top Up ,20080401  ,20080430  ,sdf  ,                          00000000431250  ,2007                                    ,  ,  ,  ,  ,  ,20080414  18:07:35,
    EMPL ,0222222,  r Cash Award ,20070701  ,20070703  ,ded  ,                          00000000023509  ,2007                                    ,  ,  ,  ,  ,  ,20080414  18:09:31,
    EMPL ,0233333,   Cash Award ,20070801  ,20070831  ,df  ,                          00000000044057  ,2007                                    ,  ,  ,  ,  ,  ,20080414  18:10:56,
    EMPL ,0244444,   Cash Award ,20080101  ,20080111  ,sf  ,                          00000000026717  ,2007                                    ,  ,  ,  ,  ,  ,20080414  18:08:29,
    BTRL ,   5140, 
    When i tested the scenario and monitored it using MDT in CC monitoring tool its giving me below mentioned error.
    The XML page cannot be displayed
    Cannot view XML input using style sheet. Please correct the error and then click the Refresh button, or try again later.
    XML document must have a top level element. Error processing resource 'http://myurlname/mdt/me...
    However if i change the occurence of DATA as some specific value for eg 4 instead of * it works fine.
    Kindly help me in solving this problem.
    Thanks,
    Aditya Verma

    Hi Madan,
    Thanks a lot for giving me the way to this. But when i tested this with the below file its giving me the same error. Please let me know if i need to do any changes to the parameters mentioned above:-
    ADSE ,ASDA,Sha  replan Fr ont Feed Contact ,2  0080509 0 8:43:25   ,        
    EMPL ,0011111,   Cash Top Up ,20080401  ,20080430  ,TPV  ,                          00000000431250  ,2007                                    ,  ,  ,  ,  ,  ,20080414  18:07:35,
    EMPL ,0222222,   r Cash Award ,20070701  ,20070703  ,TPV  ,                          00000000023509  ,2007                                    ,  ,  ,  ,  ,  ,20080414  18:09:31,
    EMPL ,0233333,  r Cash Award ,20070801  ,20070831  ,TPV  ,                          00000000044057  ,2007                                    ,  ,  ,  ,  ,  ,20080414  18:10:56,
    EMPL ,0244444,   Cash Award ,20080101  ,20080111  ,TPV  ,                          00000000026717  ,2007                                    ,  ,  ,  ,  ,  ,20080414  18:08:29,
    EMPL ,0255555,   Cash Award ,20080301  ,20080320  ,TPV  ,                          00000000027870  ,2007                                    ,  ,  ,  ,  ,  ,20080414  18:08:25,
    EMPL ,0266666,   Cash Award ,20071001  ,20071020  ,TPV  ,                          00000000020681  ,2007                                    ,  ,  ,  ,  ,  ,20080414  18:09:31,
    EMPL ,0877777,   Cash Top Up ,20080401  ,20080430  ,TPV  ,                          00000000036000  ,2007                                    ,  ,  ,  ,  ,  ,20080414  18:07:05,
    EMPL ,0888888,   Leaver Cash Award ,20071201  ,20071231  ,TPV  ,                          00000000157200  ,2007                                    ,  ,  ,  ,  ,  ,20080414  18:11:29,
    EMPL ,0899999,  S Leaver Cash Award ,20080301  ,20080331  ,TPV  ,                          00000000153530  ,2007                                    ,  ,  ,  ,  ,  ,20080414  18:07:42,
    EMPL ,0800000,  S Leaver Cash Award ,20070701  ,20070731  ,TPV  ,                          00000000012234  ,2007                                    ,  ,  ,  ,  ,  ,20080414  18:08:34,
    BTRL ,   5140,
    This the original csv file which i'll get in live. Kindly suggest as ur solution worked with other file but not working with this scv file.
    Thanks a lot,
    Aditya.

  • Problem in Sender File content conversion

    Hi all,
    my sender file structure is as follows:
    records
    header
      f1   minlength=1 MaxLenth=1
      f2   minlength=5 MaxLenth=5
      f3   minlength=7 MaxLenth=7
    detail
      f1   minlength=1 MaxLenth=1
      f2   minlength=5 MaxLenth=5
      f3   minlength=18 MaxLenth=18
    now i need to use these fixed field legth file and perform fcc.
    under fcc of communication channel
    documentname=MT_details
      rcs   header,,detail,
    header.fieldNames  header.f1,header.f2,header.f3
    header.fixedFieldLengts 1,5,7
    detail.fieldNames  detail.f1,detail.f2,detail.f3
    here I Am not using any key field
    when i test the scenario with test file
    A E123 X12345
    T T123 Textlineitem12345
    My problem is the file is not getting picked from the specified path.
    Please correct my configuration.
    Thanks,

    Check the FOLDER permission of the path.
    There may be some permissions missing to access that folder .
    Check with your BASIS or UNIX team.
    Edited by: Naresh Nelapatla on Feb 27, 2012 7:17 PM

  • Sending file using sockets (difficult)

    Hi, i have the following section of code
    (of which i am not claiming ownership) which
    implements a DCC Send command from irc.
    It accomplishes this using sockets, and while
    i understand how the code accomplishes what it
    does, i need help with a possible modification.
    Basically what i am looking to do is keep track
    of the progress of the send - so that the
    user can at any time see how much of the file
    has been sent and how much is remaining.
    If anyone has done such a thing in the past or
    has a good idea as to how this should be implemented,
    i would be greatful for their help.
    Here is the code:
    new Thread() {
                public void run() {
                    try {
                        ServerSocket ss = new ServerSocket(0);
                        ss.setSoTimeout(timeout);
                        int port = ss.getLocalPort();
                        //byte[] ip = ss.getInetAddress().getAddress();
                        byte[] ip = InetAddress.getLocalHost().getAddress();
                        long ipNum = 0;
                        long multiplier = 1;
                        for (int i = 3; i >= 0; i--) {
                            int byteVal = (ip[i] + 256) % 256;
                            ipNum += byteVal*multiplier;
                            multiplier *= 256;
                        // Rename the filename so it has no whitespace in it when we send it.
                        // .... I really should do this a bit more nicely at some point ....
                        String safeFilename = file.getName().replace(' ', '_');
                        safeFilename = safeFilename.replace('\t', '_');
                        // Send the message to the user, telling them where to connect to in order to get the file.
                        sendCTCPCommand(nick, "DCC SEND " + safeFilename + " " + ipNum + " " + port + " " + file.length());
                        // The client may now connect to us and download the file.
                        Socket socket = ss.accept();
                        socket.setSoTimeout(30000);
                        // Might as well close the server socket now; it's finished with.
                        ss.close();
                        BufferedOutputStream output = new BufferedOutputStream(socket.getOutputStream());
                        BufferedInputStream input = new BufferedInputStream(socket.getInputStream());
                        BufferedInputStream finput = new BufferedInputStream(new FileInputStream(file));
                        byte[] outBuffer = new byte[bufferSize];
                        byte[] inBuffer = new byte[4];
                        int bytesRead = 0;
                        while ((bytesRead = finput.read(outBuffer, 0, outBuffer.length)) != -1) {
                            output.write(outBuffer, 0, bytesRead);
                            output.flush();
                            input.read(inBuffer, 0, inBuffer.length);
                        output.close();
                        input.close();
                        log("+++ DCC SEND Completed to " + nick + " (" + file.getPath() + ")");
                    }

    You already have the necessary code to find the number of bytes sent at any point during the transmission. You can find out the size of the file by instantiating a RandomAccessFile before you send it, and querying for the file length.
    I suggest you make the file size and bytes sent volatile and conveniently accessible to another thread (best implemented here as an inner class?). Your new thread will need to monitor the file transfer at intervals to update the progress indicator. You can generate estimates of time remaining by measuring the average transmission rate, and extrapolating using the total file size. Classically this is done using an average, but you might be better just maintaining a list of fairly recent samples, allowing for the speed swings inherent in internet connections.
    How you update the progress indicator from your monitor thread is up to you. I suggest exposing methods in the UI for setting the progress and time remaining, and simply update them from the monitor.
    Does this help any?

  • Problem in sender file adapter

    Hi all,
      I have a sender file adapter using ftp with processing mode delete. But my input file is not getting deleted. In RWB, the adapter satus is green with msg processed sucessfully. I tried with a file name that is not available in the ftp folder, but still the adapter status is green with msg processed succesfully.
    Help me debug this error.
    Regards,
    Jai Shankar.

    Are you using Content conversion ?
    If adapter monitoring is green, and shows processed successfully, then if you have any errors , you can see in the RWB->Message Monitoring->Audit Log (Message display Tool).
    If there is no error, then try to do the cache refresh as I told. Ask Admin help for that. Restarting a Adapter engine may help you here/
    Regards,
    moorthy

  • Problem with sender file adapter

    Hi all,
    I am having a problem in reading file with complex structure,
    my structure is like this:
    Header - 1
    rows - 0 - unbound
    Footer 1
    In the recordset Structure - Header,1, Row,*, Footer,1
    The file is not being read, only if I cahnge the * to the exact number of roes type ROw it is working,
    Thnaks,
    Naama.

    Hi,
    I tried it on a simple file and it works,
    But for some reason it doesnt work on my file, I think it because the structure of the segments.
    the first line is the header and its key value is H u2013 it should appear once in the file
    the second line is the header2 and its key value is D u2013 it should appear once in the file
    the 3+4 lines is the details and its key value is L u2013 it should appear * times
    the last line is the footer and its key value is D u2013 it should appear once in the file
    Header1.
    T   H T150380149462.DAT                30/07/08 13:05:04 7 014946/2i`cpei driaz
    Header2.
    T   D  D06AA038H08052587014946245-519-60 045000WKMHDN41BP6U122056  0807230807236915    1000000      000000000000000000H,28910,22040             2828910R0000000200000000000000004830800100000001P
    Details.
    T   D  D06AA038_L_08052587014946210128910R00010020002000  
    T   D  D06AA038_L_08052587014946210128910R00010020002000  
    Footer.
    T   T T150380149462.DAT                00008  014946/2*** seq ****
    I think that because the beginning of header2 and detail is the same it does not work,
    Any Ideas?

  • Problem in displaying file thru FDTA

    hi all,
    we have a problem with FDTA while displaying the content of DME file which generated through FBWE transaction for Bill of Exchanges.
    it is showing some chinese characters in dispaly.
    but when we down load the file into PC the file getting downloaded in correct format.
    the problem here is user is looking for display functionality of the file.
    if any body came across with this issue, please share about.
    Chandra

    Hi Chandra.
    I'm facing the same problem. Have you solved it?
    Now I'm generating DME from transaction F110. And I've noticed that it happens in prod.system, in QAS or dev. no problem with showing files.
    Thanks, Mau

  • How can I send files thru iChat?

    I would like to send some of my music files to my phone but I don't have the option of sending files to my phone. Why not and is there any way I can send files to my cellphone? I've tried the Bluetooth but that tells me I have to wait 9 hrs. Is there another way that's faster?
    Thank you
    Tamara

    That's probably your SIM card (the 32MB card in the phone).
    An alternative way would be to upload the files to a webhost (you can make a free website basically anywhere on the web, tripod.com comes to mind). Keep the files to a minimum and watch your bandwidth though because the service is free, Tripod will limit your downloads/uploads to something like 10MB/day which is crazy small.
    Once the file is uploaded to your webhost, use your phones WAP browser and punch in the direct link to the file and it should download. Keep in mind that you WILL BE CHARGED for downloading data onto your phone unless your phone plan incorporates that already.
    Hope this helps,
    -Ryan

  • Problem with Sender File Content conversion

    Hi everybody,
    I have a flat file with the following structure:
    PR1xxxx
    CL1.1xxx
    ALxxx
    PTxxx
    PTxxx
    PTxxx
    CL1.2xxx
    ALxxx
    PTxxx
    PTxxx
    Cl1.3xxx
    PR2xxx
    CL2.1
    Alxxx
    PTxxx
    Ptxxx
    CL2.2xxx
    ALxxx
    PR3xxx
    I need to send an IDOC (ORDERS05) per CL and I also need that the PR goes together with the CL.
    Something like that:
    IDOC 1
    PR1xxx
    CL1.1xxx
    ALxxx
    PTxxx
    PTxxx
    PTxxx
    IDOC 2
    PR1xxx
    CL1.2xxx
    ALxxx
    PTxxx
    PTxxx
    IODC 3
    PR2xxx
    CL2.1xxx
    The problem is that I am not able to attach the PR with each CL because the PR is written once at the beginning.
    I have tested all the posibilities in the content conversion area but I don`t find the way to achiveve that.
    Maybe, Have I to do something in the mapping program?
    Nested substructures are possible in the File Content Conversion?
    Any idea?
    Thanks for everything

    We can handle this in mapping as follows
    Crate an Intermediate structure Identical to your input structure. Just you need to add an sub element (Let’s say "T" to your CL node.
    This sub element will be used to remember CL node belongs to which PR node.
    Map your Input structure to Intermediate structure.
    While mapping PR Node of input to PR Node of Intermediate structure use a user defined function as follows
    Integer ii;
    GlobalContainer g;
    g=container.getGlobalContainer();
    Object o= g.getParameter("_&HLID");
    if (o==null) ii=new Integer(0);
    else
    ii =(Integer)o;
    ii =new Integer(ii.intValue()+1);
    g.setParameter("_&HLID",ii);
    Use another user defined function to retrieve the value of this _&HLID and put it to T as follows:
    GlobalContainer g;
    g=container.getGlobalContainer();
    Object o= g.getParameter("_&HLID");return o.toString();
    For all other fields just do a 1:1 mapping.
    Then
    Map your intermediate structure to destination structure (IDOC)
    Here the only catch is:
    For populating the value of PR for each CL
    Pass both the element T and the element of PR from which you want to pick the value to a user-defined function (raise the context of both elements to the top node).
    In array a we have the value of T
    In array b we have the value of element of PR
    int j=0;
    for(int k=0;k<b.length;k++){
    for (int i=0;i<a.length;i++)
         if (a<i>.equals(new Integer(j+1).toString())){
              System.out.println(b[j]);
         j=j+1;
    Hope this takes care of your problem.
    If you don't get anything please get back to me.
    Abinash

  • Send files through Sockets

    how do i send an entire file through a socket...?
    thank you....

    [http://forums.sun.com/thread.jspa?forumID=11&threadID=390636] this may help you

Maybe you are looking for

  • [b]export data from a table to a csv or .txt file[/b]

    hi plz i need help in how to export data from a table to a csv or .txt file

  • Install OS X on replacement macbook air HD from Lion

    Hi, My Macbook air hard drive recently gave up after 4 years (therefore out of warranty) so I bought a replacement hard drive for it. At the time I was running snow leopard on my imac and understood I could use it's optical drive to install snow leop

  • Outlook 2010 Adobe PDF maker fails

    I work for a major university that currently uses Outlook 2010. We get high volumes of emails and like to convert said emails to archive them for our records. There seems to be a problem with the amount of emails that can be converted, I've yet to de

  • Developer 6.0 Eap release

    Hi, The only Oracle product I have installed is the RDBMS on Solaris. I assume from the Developer documentation that I can install Developer on my NT box even though my server is on Solaris. When I run setup it begins to install some support files bu

  • Effective price becomes negative

    Hello, When net weight is changed in PO, I am getting the error message no. 328 i.e "effective price becomes negative please correct" Can you please explain what may be the reason for this and how to correct. PO is thirdy party PO and invoice is post