Transfer files using Java Socket

Source: Internet
Author: User

Recently, in a course design and chat system, a function is to transfer files. I used UDP datagram to transfer files first, but I found that packet loss occurs when the transmitted files are too large, therefore, you can use the TCP connection of the Java Socket to transfer files. The speed of file transmission in the LAN is still acceptable.

The following is part of the code, which may not be run independently, because it involves a graphical interface and other classes, but it can be changed a little. I uploaded the source code to csdn. Yes: success!

The system can communicate with multiple clients and servers to transmit files. The interface is not very nice, haha!

The code for the two main types of file transfer is pasted below.

Accept Class: <br/> package Org. loonsoft. server; </P> <p> Import Java. io. datainputstream; <br/> Import Java. io. dataoutputstream; <br/> Import Java. io. file; <br/> Import Java. io. fileoutputstream; <br/> Import Java. io. ioexception; <br/> Import java.net. serversocket; <br/> Import java.net. socket; <br/> Import Java. util. concurrent. executorservice; <br/> Import Java. util. concurrent. executors; </P> <p> Import javax. swing. jdialo G; <br/> Import javax. swing. joptionpane; </P> <p> Import Org. loonsoft. utils. fileprogressbar; <br/> Import Org. loonsoft. utils. frameutils; <br/> Import Org. loonsoft. utils. paramaterutils; <br/> Import Org. loonsoft. utils. savefiledialog; </P> <p> public class receivefileservice implements runnable {</P> <p> private executorservice exec = executors. newcachedthreadpool (); </P> <p> private serversocket = nu Ll; </P> <p> private Socket socket = NULL; </P> <p> private frameutils frame = NULL; </P> <p> Public receivefileservice (frameutils frame) {</P> <p> This. frame = frame; </P> <p> try {</P> <p> serversocket = new serversocket (paramaterutils. getfileport (); <br/> // serversocket = new serversocket (8881); </P> <p> system. out. println ("file Listening Starts ..... "); </P> <p >}catch (ioexception e) {</P> <p> E. printstacktrace (); </P> <p >}< br/>}< /P> <p> Public void run () {</P> <p> while (true) {</P> <p> try {</P> <p> socket = serversocket. accept (); </P> <p> // system. out. println (socket. getport (); </P> <p> exec.exe cute (new handler (socket, frame ). run (); </P> <p> // socket. close (); <br/> // serversocket. close (); </P> <p >}catch (ioexception e) {</P> <p> E. printstacktrace (); <br/>}</P> <p> // public static void main (string [] ARGs) {<br/> // new THR EAD (New receivefileservice ()). start (); <br/> //} </P> <p >}</P> <p> class handler {</P> <p> private Socket socket = NULL; </P> <p> private frameutils frame = NULL; </P> <p> private fileprogressbar bar = NULL; </P> <p> private final jdialog bardialog = new jdialog (); </P> <p> Public handler (Socket socket, frameutils frame) {</P> <p> This. socket = socket; </P> <p> This. frame = frame; </P> <p >}</P> <p> private datainputstream g Etdatainputstream () throws ioexception {</P> <p> return New datainputstream (socket. getinputstream (); </P> <p >}</P> <p> private dataoutputstream getdataoutputstream () throws ioexception {</P> <p> return New dataoutputstream (socket. getoutputstream (); </P> <p >}</P> <p> private string selectedpath () {</P> <p> return New savefiledialog (). getpath (FRAME); <br/>}</P> <p> private void runbar (INT maxsize) {</P> <p> bar = N EW fileprogressbar (); </P> <p> bar. setsize (maxsize); </P> <p> bardialog. setlocation (150, 20); </P> <p> bardialog. settitle ("file receipt progress"); </P> <p> bardialog. setsize (250, 50); </P> <p> bardialog. add (Bar. getbar (); </P> <p> bardialog. setenabled (false); </P> <p> bardialog. setvisible (true); </P> <p> New thread (bar ). start (); </P> <p >}</P> <p> Public runnable run () {</P> <p> return New runnable () {</P> <p> Public void run () {</P> <p> try {</P>/ P> <p> datainputstream in = getdatainputstream (); </P> <p> dataoutputstream OS = getdataoutputstream (); </P> <p> byte [] DATA = new byte [1024]; <br/> while (in. available () <= 0); // synchronous </P> <p> int Len = in. read (data); </P> <p> string [] STR = new string (data, 0, Len, "UTF-8 "). split (";"); </P> <p> string Path = selectedpath (); </P> <p> If (Len! =-1) <br/> path + = STR [0]; // STR [0] is the file name plus type </P> <p> system. out. println (PATH); </P> <p> OS. write ("START ". getbytes (); </P> <p> OS. flush (); </P> <p> file = new file (PATH ); </P> <p> dataoutputstream out = new dataoutputstream (<br/> New fileoutputstream (File); </P> <p> system. out. println ("start receiving ..... "); </P> <p> int countsize = 0; </P> <p> runbar (integer. parseint (STR [1]); // progress bar for receiving the Startup File </P> <p> while (LEN = in. read (data ))! =-1) {</P> <p> out. write (data, 0, Len); </P> <p> countsize + = Len; </P> <p> bar. setsendsize (countsize); </P> <p >}</P> <p> OS. close (); </P> <p> out. flush (); </P> <p> out. close (); </P> <p> in. close (); </P> <p> bardialog. setvisible (false); </P> <p> bardiible. dispose (); // The Progress of closing the file display box </P> <p> joptionpane. showmessagedialog (frame, "file accepted! "); </P> <p >}catch (ioexception e) {</P> <p> E. printstacktrace (); </P> <p >}finally {</P> <p> try {<br/> socket. close (); <br/> system. out. println ("close .... "); <br/>}catch (ioexception e) {<br/> E. printstacktrace (); <br/>}</P> <p> }; </P> <p >}< br/> sending class: <br/> package Org. loonsoft. client; </P> <p> Import Java. io. datainputstream; <br/> Import Java. io. dataoutputstream; <br/> Import Java. io. file; <br /> Import Java. io. fileinputstream; <br/> Import Java. io. ioexception; <br/> Import java.net. socket; <br/> Import java.net. unknownhostexception; </P> <p> Import Org. loonsoft. utils. paramaterutils; <br/> Import Org. loonsoft. utils. sendfileprogressbar; </P> <p> public class sendfileservice implements runnable {</P> <p> private Socket socket = NULL; </P> <p> private string Path = NULL; </P> <p> private sendfileprogressbar Bar = NULL; </P> <p> Public sendfileservice (sendfileprogressbar bar) <br/> throws unknownhostexception, ioexception {</P> <p> This. bar = bar; </P> <p> socket = new socket (paramaterutils. getip (), paramaterutils <br/>. getfileport (); <br/> // socket = new socket ("127.0.0.1", 8881 ); </P> <p >}</P> <p> private dataoutputstream getdataoutputstream () throws ioexception {</P> <p> return New dataoutputstream (socket. getou Tputstream (); </P> <p >}</P> <p> private datainputstream getdatainputstream () throws ioexception {</P> <p> return New datainputstream (socket. getinputstream (); </P> <p >}</P> <p> private string getpath () {<br/> return path; <br/>}</P> <p> Public void setpath (string path) {<br/> This. path = path; <br/>}</P> <p> Public void run () {</P> <p> try {</P> <p> datainputstream READ = new datainputstream (New fileinputstream (<B R/> New file (getpath (); </P> <p> bar. setsize (read. available (); // set the total length of the file </P> <p> system. out. println (read. available (); </P> <p> dataoutputstream OS = getdataoutputstream (); </P> <p> datainputstream in = getdatainputstream (); </P> <p> string filename = path. substring (path. lastindexof ("//") + 1); // obtain the file name plus type </P> <p> system. out. println (filename); </P> <p> OS. write (filename + ";" + read. available ()). getbytes ("UTF-8" ); // Transmits the file name and file size to the receiver </P> <p> byte [] DATA = new byte [1024]; </P> <p> int Len = in. read (data); </P> <p> string start = new string (data, 0, Len); </P> <p> int sendcountlen = 0; </P> <p> If (start. equals ("START") {</P> <p> New thread (bar ). start (); // start the File progress bar thread </P> <p> while (LEN = read. read (data ))! =-1) {</P> <p> OS. write (data, 0, Len); </P> <p> sendcountlen + = Len; </P> <p> bar. setsendsize (sendcountlen); </P> <p >}</P> <p> OS. flush (); </P> <p> OS. close (); </P> <p> Read. close (); </P> <p >}</P> <p >}catch (ioexception e) {</P> <p> E. printstacktrace (); <br/>}finally {</P> <p> try {<br/> socket. close (); <br/>}catch (ioexception e) {<br/> E. printstacktrace (); <br/>}</P> <p >}< br/>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.