Pls help: server send a file upon client's request

I just started learning Java and I'm trying to write a simple file transfer program. My problem should be in the transfer part. Code as follows:
Client side:
package p2pclient;
import java.io.*;
import java.net.*;
public class P2PClient {
public static void main(String argv[]) throws Exception
  String filename;
  try {
  Socket clientSocket = new Socket("localhost", 6783);
  BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
  filename = inFromUser.readLine();
  DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
  outToServer.writeBytes(filename);
  String newname = "C:\\" + filename;
  File file = new File(newname);
  byte[] Byte = new byte[1120];
  DataInputStream inFromSocket = new DataInputStream(clientSocket.getInputStream());
  FileOutputStream fout = new FileOutputStream(file);
  int reads;
  while((reads = inFromSocket.read(Byte)) != -1){
  fout.write(Byte, 0, Byte.length);
  clientSocket.close();
  catch (java.io.IOException e) {
      System.err.println("error connecting to " + "Daniel-Ding" + ":" + e);
      return;
}On the server side:
package p2pserver;
import java.io.*;
import java.net.*;
import java.util.logging.*;
class FileTransfer implements Runnable {
  private Socket connectionSocket;
  FileTransfer(Socket connectionSocket) {
    this.connectionSocket = connectionSocket;
  public void run(){
        try {
            String fileName;
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            fileName = inFromClient.readLine();
            System.out.println("received filename: "+ fileName);
            File fl = new File(fileName);
            byte[] filebuffer = new byte[1120];
            FileInputStream fin = new FileInputStream(fl);
            int bytesRead;
        while ((bytesRead = fin.read(filebuffer)) != -1) {
            connectionSocket.getOutputStream().write(filebuffer, 0, bytesRead);         
            connectionSocket.close();
        } catch (IOException ex) {
            Logger.getLogger(FileTransfer.class.getName()).log(Level.SEVERE, null, ex);
class P2PServer {
    public static void main(String argv[]) throws Exception
        ServerSocket welcomeSocket = new ServerSocket(6783);
        while(true) {
            Socket connectionSocket = welcomeSocket.accept();
            FileTransfer ft;
            ft = new FileTransfer(connectionSocket);
            Thread thread = new Thread(ft);
            thread.start();
}I can see an empty file with the name of 'newname' in my C drive but no data transfered.
Thanks a lot in advance.

Hi Peter,
Sorry to bother you again. I tried to increase the size of the buffer. The speed improved but the transfered file quality became intolerable. I tested it with some mp3 files and found that with large buffer size there was a lot of noise in the transfered mp3s. Any idea what I can do to optimize this trade-off?
Many thanks.
Best,
Daniel

Similar Messages

  • Edge Server send RST packet to Client

    Hi all,
    I'm meeting an issue, please help me!
    I'm setting up a testing LAB. After I deployed Edge Server, everything may be fine. But Client connects to Edge server, after TLS handshake, the server send RST packet to
    Client. Please refer picture below.
    I used CA built on Domain Controller server to assign Cert to internal and external interface of Edge server. I know I should use a public CA on Internet to assign Cert to external interface, but I'm setting LAB for testing, so I used internal CA. And my
    domain internal and external are the same (e.g: internal is edge.sip96x2.com and external is access.sip96x2.com). From Client, I installed Root CA Cert downloaded from CA on Domain Controller. Client from external doesn't
    have DNS server, instead of using Hosts file, the Host file includes:
    "100.20.252.12     access.sip96x2.com"
    I don't know what is information need to show here, if you required any information, please let me know, thanks so much!

    To work with your Lync Client from External over the edge, the Lync Client has to reach
    Access Edge, Audio/Video Edge and Web Edge IP.
    To login to your Lync Edge you can use the lync Manual Configuration access.sip96x2.com:443.
    You should use the host fqdn for internal Connection and the three needed External FQDN for the edge.
    To use a private CA ist allways possible for a Lab.
    http://ocsguy.com/2010/11/21/deploying-an-edge-server-with-lync/
    regards Holger Technical Specialist UC

  • Sending xml file from client to servlet

    Hi,
    I am writing the server component of an applcation, such that it will receive xml files from the clients(standalone application similar to javaSwing stuff but it's coded in C#), and the servlet will have to extract the data from the xml file and update the mySql database. it will also fulfill the client's request for xmlFiles (and extract data from DB, format to xml file and send back to client)
    I'm new to implementing the servlet receiving files from clients so would need some help.
    I've got 3 questions to ask:
    1) How does the servlet receive/returns the xml file from the client as a series of httpPost request/response. Do i send a File or the file's contents as a String to/from the client?
    2) Is it also a must to use socket for the file transfers? I have read in other posts about sockets as well as HttpURLConnection but i don't quite understand.
    3) When I send a file back to the client(client is standalone application written in C# whereas server is coded in java), what do i specify for the HttpResponse.setContentType() in my servlet? (i'm returning the xml file to client)
    Would really appreciate for any help rendered. If you have any useful links, would appreciate them too. Thanks a lot.
    Karen

    I've got 3 questions to ask:
    1) How does the servlet receive/returns the xml file
    from the client as a series of httpPost
    request/response. Do i send a File or the file's
    contents as a String to/from the client?The server will listen on some port for requests. The client has to open a socket to this server to send the file as string to the server.
    see http://java.sun.com/docs/books/tutorial/networking/index.html
    >
    2) Is it also a must to use socket for the file
    transfers? I have read in other posts about sockets as
    well as HttpURLConnection but i don't quite
    understand.You use HttpURLConnection to make a request using the http protocol, instead of opening a socket and then writing the html headers yourself.
    3) When I send a file back to the client(client is
    standalone application written in C# whereas server is
    coded in java), what do i specify for the
    HttpResponse.setContentType() in my servlet? (i'm
    returning the xml file to client)Its up to your receiving program how to interpret this though, so you probably dont need this.

  • With webutil-client_host, send txt file to client printer

    hi,
    I wanna to learn how to send a txt file to client default printer(local or network),
    I created txt file at client disk, and try to send printer directly,
    just try some statement looks like below;
    a.client_host('cmd /c start print C:\TEMP399899.txt /d:lpt1');
    b.client_host('cmd /c start copy C:\TEMP399899.txt lpt1');
    I do not know the command prompt syntax, please help me, reference me,
    thanks

    Hi,
    on a command line type
    print /?
    for the help of how to print documents. On XP this help is
    PRINT [D:device] [[drive:][path]filename[...]]
    /D:device Specifies a print device.
    Frank

  • Robo Help Server 8 Publishing files to wrong location

    Hi
    I have recently installed a trail verstion of Robo Help 8 server.  All appears to be ok with the install I can access the website and log into the admin portal etc...  The only diffrence from the default install is that I have configured tomcat to use port 80 rather than 8080.
    However I am having a problem whenever i try to publish a help file from Robo Help 8, I input all of the details of the server <Server IP>/robohelp/server
    put in the default admin username and password and select the general area to publish the help file to.  All of the files appear to publish ok from Robo Help 8 and no errors are receved.
    When I log onto the admin portal of the website the there is nothing displayed in the projects window.  I have check the local disk of there server were robo help is installed and i think the problem may be that the server is putting the files in the wrong location.
    I can see that a folder has been created in the following location
    C:\Program Files\Adobe\Adobe RoboHelp Server 8\robo\server\general\projects\TestProject
    with the following folders within it
    resource
    webhelp_skin_files
    whdata
    whxdata
    However none of these folders contain any data.
    All of the files apper to be uploading to C:\ not the above directory wich is what i would expect.
    If a copy the files that have been uploaded to C:\ to C:\Program Files\Adobe\Adobe RoboHelp Server 8\robo\server\general\projects\TestProject and restart the tomcat service the project then shows in the project window.  However when i click view project all i get is a blank screen.  I have searched the forum but cannot find anyone having a similar issue.
    Any help would be gratley appriciated.
    Below is the config of the Server
    Windows 2003 Server IIS not installed
    Java 6.21
    Tomcat 6.0.29
    Robo Help Server 8

    aha!
    If the firewall is on, turn it off.
    JC

  • Pls help in webform.cfg file..sorry for many postings since i am struggling

    Hi all,
    HMMM.. i fixed the problem.. but still need some help
    in my url i specified local host instead of servername and i am able to run the form on the web.
    http:localhost:8888/forms90/f90servlet?form=....etc(working fine)
    instead of
    http:itxkjdkk:8888/forms90/f90servlet?form=
    This is throwing error FRM92050
    but the problem is when ever i run the fmb from form builder in the IE browser
    it is taking the http://itxkjdkk:8888/forms90/f90servlet..so throwing error so i have to manually replace the url in browser to localhost:8888
    How can i set this through in formsweb.cfg..i did try to
    http:localhost:8888/forms90/f90servlet?form=....in server_url parameter of the
    formsweb.cfg but still it is taking http://itxkjdkk:8888/forms90/f90servlet when i run the form on web..
    pls help
    asp

    Hi,
    In Builder Preferences dialog, under the runtime tab,
    change the Application Server URL to the desired URL
    and run the form.
    HTH.
    Regards,
    ArunHi Arun,
    Thanks for help..
    As you suggested i have to manually set the application server url each time when i invoke the form builder..
    I really dont understand why forms behaving like this. when i pass the servername it is throwing error and if i pass localhost instead of server name it is working fine.
    It is taking the default application url value : http://servername:8888//forms90//...
    but it is throwing error FRM 92050
    if i pass http://localhost:8888/forms90... good everything is fine.. now
    now i want to change default application url..i tried it in formsweb.cfg
    server_url=http://localhost:8888/forms90/f90servelet..
    if i run the form with above parameter...at least IE is not invoked..
    if that parameter value is /forms90/f90servelet then atleast it will invoke IE and throwing error 92050
    Pls help
    asp

  • Pls help in sending multiple resposes after analysing the sequential commands from the device

    Hi all
    pls help me in  sending sequential responses for the different commands. For example,i have to send the response1 for command1 then again host wll send the some other command ,say command 2  after receiving response 1,then again i have to respond to the corresponding command.i m using the pci-6221 card not tradition DAQcard.
    regards,
    nitin

    Hello nitin,
    It sounds like you are looking for some examples on how to program your
    6221 DAQ board.  I highly reccomend taking a look at the LabVIEW
    shipping examples that install with the DAQ driver.  To access
    them, open the NI Example Finder by going to the menu bar of a VI and
    selecting Help >> Find Examples...
    If you have any specific questions, please feel free to ask!
    Eric
    DE For Life!

  • Send to files to client

    Hi,
    I need to send two separate files using a single HttpResponse. II don't know how to do that, and I'm trying to make a zip file that contains thw two files. The problem is that the two files doesn't exisist on the server, and I don't know how t o put a String Stream into a ZipStream . Some one could help me?
    Thanks in advance
    Nicola Salvo

    I've solved using:
    private void extract(OutputStream out){
        PrinterWriter pw = new PrinterWriter(out)
        try{
        finally pw.flush
    ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
    out.putNextEntry(new ZipEntry("feat.csv");
    extract(out)
    out.colseEntry();
    out.close()Thank for your answer :)

  • HELP Server Write To File

    Hi, i have to chat programs that use different techniques. i have done tcp but cant seem to do rmi.
    i want to be able to log the messages to a file
    can some one please help?
    import java.rmi.*;
    import java.rmi.server.*;
    public class RMIChatServerImpl3 extends UnicastRemoteObject implements RMIChatServer3
         private static String [] message;
         private static int messageCount = -1;
         public RMIChatServerImpl3 () throws RemoteException
              //super ();
              message = new String [100]; //"<NO MESSAGE>";
         public String getMessage (int n) throws RemoteException
              System.out.println ("n = " + n + " messageCount = " + messageCount);
              while (n > messageCount);
              System.out.println ("message retrievd = " + message[n]);
              return message [n];
         public void putMessage (String s) throws RemoteException
              message[++ messageCount] = s;
              System.out.println ("message stored = " + message[messageCount] + ", messageCount = " + messageCount);
         public static void main (String args []) throws Exception
              RMIChatServerImpl3 t = new RMIChatServerImpl3 ();
              Naming.rebind ("//localhost/RMIChatServer3",  t);
    }

    here is my attempt:
                System.out.println("Attempting file write to d:/Java/TestServlet...");
                File f = new File( "blah.txt" );
                FileWriter fw = new FileWriter( f );
                fw.write( fromClient );
                fw.close();
                System.out.println( " -- allowed -- ");(this is taken from the tcp method which works)

  • Help with sending pdf files

    how do i send a pdf file i receieved in a email or can i go to my email and print it off

    In Adobe reader, Click File > Send File, and the file will be put as an attachment in your email client.
    Else just do a manual insert like any other attachment.
    Cheers
    [ email signature removed - see http://forums.adobe.com/docs/DOC-3731 ]

  • Sending .mov file to client and can't burn to DVD

    I am sending a proof .mov file to a client that is windows based. Is there any burning software that will burn a .mov file and play on a windows machine without me converting it to a .AVI file? If I do have to convert it to a .AVI file will there be resolution or quality loss and will they even be able to burn that? They have NERO as their burning software, im using toast titanium and have quicktime pro. thanks

    Toast 8 is the answer. Clients want to get something they can play EASY. DVD works on the TV and PC and needs nothing software wise. Worth the money. Plus the video quality looks good enough but really is not good enough to steal and edit.

  • Pls help decompress jsonl4 bookmark file

    After one of latest Firefox update (think it was around version 32) the bookmark file was compressed as "bookmarks_<date>....==.jsonlz4 file. After an update the new Firefox was not able to retrieve the compressed bookmark. I hope that here is a way to decompress this file outside the Firefox and retrieve it either as json or html file or a file that is retrievable by latest Firefox (34).
    The file is found in the following location:
    C:\<user name>\AppData\Roaming\Mozilla\Firefox\Profiles\mvf52dyv.default
    bookmark\bookmarks-2014-11-01-15....==.lzh
    bookmarkbackups\bookmarks-2014-11-01_15_....==.jsonlz4
    The “mvf52dyv” is the from the old installation. The new one is tw145s6s.default
    To save it I renamed the “old” Mozilla directory to Mozilla_ before uninstalling and reinstalling a clean new version. Copied back the "old" jsonlz4 and "places.sqlite" to new "bookmarkbackups" directory but still no luck.
    One observation is that the new firefox (34 – just updated)) had jsonlz4 file and places.sqlite in a bookmarkbackups directory, while older versions has it at “<...>.default” directory level. Also, the new Firefox does not have bookmark directory, where the old one has in it bookmarks-<date>==.lzh file.
    I did try suggestion from the Firefox help pages to copy the old bookmarkbackups (with places.sqlite) into place of the new one, but that did not help. Even tried to copy the whole old mvf52dyv.default under new Mozilla directory, but this also did not work.
    Is this old bookmark lost for good or there is a hope to restore it? I will appreciate any help in restoring the content of the old bookmark.
    Regards
    Darko

    Thank you for the replay. With few attempts I was able to restore the “old” bookmark. Unfortunately, what I thought to be the old one has already been overwritten by an empty bookmark either during an update or one crash that happen around that time.
    The interesting thing is that this “old” jsonlz4 file has date in name bookmarkbackups-2014-11-1-..., although the file time stamp is 9-26-2014, which I hoped contain the old bookmarks. The Sep date led me to believe that this is the old bookmark.
    Can by any chance one of the two non-zero length files in minidump directory contain any sign of the lost bookmark?
    For my benefits, where are the bookmarks stored now? With few sites added in the bookmark, only saw the places.sqlite being updated (in Roaming\...firefox\Profiles\<...>default\places.sqlite*). Did not find any file with name bookmark.*. At one exit saw boomarkbackups …. jsonlz4 file being updated (time stamp).
    Regards

  • I need help to send idocs from 1 client to another , both in different systems

    Hi all,
    I am new to Idoc. I am trying to use idoc to send some table records of a custom table created in client 800 to client 020, both clients are in different systems.
    I found examples of same scenario but for both clients in same system..
    what changes should I make then to be able to send idoc .
    any link showing step by step instructions would be great.
    Thank you.

    1. If you insist on keying in Pr; use the color or chroma key. If you want a quality product use a compositor like AE to do your keying.
    2. Export to Encore

  • Send a file to client

    Hi!
    I have to send a byte array as a file to the browser. How do I convert byte[] into a resource-type context node, so it can be downloaded?
    Thanks!

    Hi,
    this code does it the other way, but I may be helpfull:
    private byte[] getByteArrayFromResource(IWDResource resource)
    throws FileNotFoundException, IOException {
    InputStream in = resource.read(false);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int length;
    byte[] part = new byte[10 * 1024];
    while ((length = in.read(part)) != -1) {
    out.write(part, 0, length);
    in.close();
    return out.toByteArray();
    Regards, Bernd

  • TD or Old Toad pls help: Renamed iPhoto Library File....no pics in iPhoto6

    I am working on my parents computer... they have iPhoto 6 and I renamed the iPhoto Library folder in Finder. Obviously this is not a good idea since now there is no content (pics) in iPhoto. 
    This action made a new folder (with the new name) in Finder's 'pictures' file. So, I tried to copy and paste (or maybe I highlighted & moved it, can't recall) the contents of the newly named folder back under the 'iphoto library' folder however, that did not make the photos reappear in iPhoto.
    After moving (I think I highlighted & dragged) the file contents of the newly named folder back in the 'iPhoto Library' folder, I deleted the newly named/created file.
    The individual pics seem to be in the modified & originalsfolder but I do not know how to get them back into iPhoto..
    I attempted to rebuild the iPhoto library but it seemed like an empty request since the computer didnt do anything when this option was selected.
    I know there is a solution but I dont know the smartest nextstep. I have read related discussions that almost provide a solution.
    Currently, I need to figure out a way to:
    1) get what seems to still exist in the modified & original folders back into iPhoto even if it means loosing album names, keywords. I am hoping this route doesn’t wipe out dates from when the images were taken. If there is a way to get them back into iPhoto this route, I need instructions.
    or,
    2) I have a back up of the entire HD on an external HD. Would itbe best to somehow use that to replace what I have on the computer HD? I do not know how to do this so for sure need guidance.
    or,
    3) Find another solution, quickly…
    Thank you so very much as I need to fix this ASAP.

    See my reply in your other thread.
    Regards
    TD

Maybe you are looking for