Java Socket multi-thread network transmission of multiple files

Source: Internet
Author: User
Tags sendfile

Due to the need to study the use of Java Socket to transfer files, due to the need to transfer multiple files, so the use of multi-threaded design. Each client thread creates a socket connection, and each socket connection transmits a file. Each serversocket on the server receives a socket connection and creates a thread to receive files from the client.

1. Server

Import java. io. bufferedInputStream; import java. io. bufferedOutputStream; import java. io. dataInputStream; import java. io. dataOutputStream; import java. io. fileOutputStream; import java.net. serverSocket; import java.net. socket; import java. util. concurrent. executorService; import java. util. concurrent. executors; public class TransferServer {private int defaultBindPort = Constants. DEFAULT_BIND_PORT; // Mo The listening port number is 10000 private int tryBindTimes = 0; // The number of initial ports bound is set to 0 private ServerSocket serverSocket; // The service socket waits for the connection and file of the other party to send private ExecutorService executorService; // The thread pool private final int POOL_SIZE = 4; // The thread pool size of a single CPU/*** the constructor without parameters. Use the default port number * @ throws Exception */public TransferServer () throws Exception {try {this. bingToServerPort (defaultBindPort); executorService = Executors. newFixedThreadPool (Runtime. g EtRuntime (). availableProcessors () * POOL_SIZE); System. out. println ("Number of opened threads:" + Runtime. getRuntime (). availableProcessors () * POOL_SIZE);} catch (Exception e) {throw new Exception ("port binding failed! ") ;}}/*** Parameter-based constructor. Select the user-specified port number * @ param port * @ throws Exception */public TransferServer (int port) throws Exception {try {this. bingToServerPort (port); executorService = Executors. newFixedThreadPool (Runtime. getRuntime (). availableProcessors () * POOL_SIZE);} catch (Exception e) {throw new Exception ("port binding failed! ") ;}} Private void bingToServerPort (int port) throws Exception {try {serverSocket = new ServerSocket (port); System. out. println (port); System. out. println ("service started! ");} Catch (Exception e) {this. tryBindTimes = this. tryBindTimes + 1; port = port + this. tryBindTimes; if (this. tryBindTimes> = 20) {throw new Exception ("You have tried many times, but still cannot bind to the specified port! Please re-select the bound default port number ");} // recursively bind the port this. bingToServerPort (port) ;}} public void service () {Socket socket = null; while (true) {try {socket = serverSocket. accept (); executorService.exe cute (new Handler (socket);} catch (Exception e) {e. printStackTrace () ;}} class Handler implements Runnable {private Socket socket; public Handler (Socket socket) {this. socket = socket;} public void run () {System. out. p Rintln ("New connection accepted" + socket. getInetAddress () + ":" + socket. getPort (); DataInputStream dis = null; DataOutputStream dos = null; int bufferSize = 8192; byte [] buf = new byte [bufferSize]; try {dis = new DataInputStream (new BufferedInputStream (socket. getInputStream (); String savePath = Constants. RECEIVE_FILE_PATH + dis. readUTF (); long length = dis. readLong (); dos = new DataOutputSt Ream (new BufferedOutputStream (new FileOutputStream (savePath); int read = 0; long passedlen = 0; while (read = dis. read (buf ))! =-1) {passedlen + = read; dos. write (buf, 0, read); System. out. println ("file [" + savePath + "] received:" + passedlen * 100L/length + "%");} System. out. println ("file:" + savePath + "received! ");} Catch (Exception e) {e. printStackTrace (); System. out. println (" failed to receive file! ") ;}Finally {try {if (dos! = Null) {dos. close () ;}if (dis! = Null) {dis. close () ;}if (socket! = Null) {socket. close () ;}} catch (Exception e) {e. printStackTrace () ;}}} public static void main (String [] args) throws Exception {new TransferServer (). service ();}}

2. Client

Import Java. io. bufferedinputstream; import Java. io. datainputstream; import Java. io. dataoutputstream; import Java. io. file; import Java. io. fileinputstream; import java.net. socket; import Java. util. arraylist; import Java. util. random; import Java. util. vector; import Java. util. concurrent. executorservice; import Java. util. concurrent. executors; public class transferclient {Private Static arraylist <string> Filelist = new arraylist <string> (); Private string sendfilepath = constants. send_file_path;/*** parameter-based constructor. You can set the folder * @ Param filepath */Public transferclient (string filepath) {getfilepath (filepath );} /*** the constructor without parameters. Use the default folder */Public transferclient () {getfilepath (sendfilepath);} public void Service () {executorservice = executors. newcachedthreadpool (); vector <integer> vector = getrandom (filelist. size (); For (integer INTEGER: vector) {string filepath = filelist. get (integer. intvalue (); executorservice.exe cute (sendfile (filepath) ;}} private void getfilepath (string dirpath) {file dir = ne W file (dirpath); file [] files = dir. listfiles (); If (Files = NULL) {return;} For (INT I = 0; I <files. length; I ++) {If (files [I]. isdirectory () {getfilepath (files [I]. getabsolutepath ();} else {filelist. add (files [I]. getabsolutepath () ;}} private vector <integer> getrandom (INT size) {vector <integer> V = new vector <integer> (); random r = new random (); Boolean B = true; while (B) {int I = R. nextin T (size); If (! V. contains (I) v. add (I); If (v. size () = size) B = false;} return V;} Private Static runnable sendfile (final string filepath) {return New runnable () {private Socket socket = NULL; private string IP = "localhost"; private int Port = 10000; Public void run () {system. out. println ("start sending file:" + filepath); file = new file (filepath); If (createconnection () {int buffersize = 8192; byte [] Buf = new byte [Buffersize]; try {datainputstream FCM = new datainputstream (New bufferedinputstream (New fileinputstream (filepath); dataoutputstream dos = new dataoutputstream (socket. getoutputstream (); dos. writeutf (file. getname (); dos. flush (); dos. writelong (file. length (); dos. flush (); int READ = 0; int passedlen = 0; long length = file. length (); // obtain the length of the file to be sent. read (BUF ))! =-1) {passedlen + = read; system. out. println ("completed file [" + file. getname () + "] percentage:" + passedlen * 100l/Length + "%"); dos. write (BUF, 0, read);} dos. flush (); FCM. close (); dos. close (); socket. close (); system. out. println ("file" + filepath + "transfer completed! ");} Catch (exception e) {e. printstacktrace () ;}} private Boolean createconnection () {try {socket = new socket (IP, Port); system. out. println ("connection to the server successful! "); Return true;} catch (exception e) {system. Out. println (" failed to connect to the server! "); Return false ;}};} public static void main (string [] ARGs) {New transferclient (). Service ();}}

3. Constant class

    public interface Constants {                public final static String RECEIVE_FILE_PATH = "E:\\receive\\";                    public final static String SEND_FILE_PATH = "E:\\send";                    public final static int DEFAULT_BIND_PORT = 10000;      }  

From [http://software.intel.com/zh-cn/user/817741]

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.