Java code for sending and receiving socket files (Java sticks to the package's personal contact)

Source: Internet
Author: User

This is a simple example that contains the sender and receiver. The sender sends the file name and content to the receiver, and the receiver saves the received file on the disk. The receiving end can receive files from multiple sending ends at the same time, but it does not process files with the same name.

In this example, a simple protocol is designed. The sent content is as follows:

File Name Length (4 bytes)-file name-File Content Length (4 bytes)-file content.

The receiving end is also parsed according to this structure. We recommend that you first read the client class and then the server class.

Import java. Io .*;

Import java.net. serversocket;

Import java.net. Socket;

/**

* Simple example of File Sending and receiving

*/

Public class filetrasmission {

// Program entry

Public static void main (string [] ARGs) throws exception {

Int Port = 7788;

New server (port, "C: \ save \"). Start ();

New client (). sendfile ("127.0.0.1", port, "C: \ lost in the last year. txt ");

}

}

/**

* Acceptor. You can receive files sent from multiple senders at the same time. But if the file is the same name, it will be messy.

*/

Class server {

Private int listenport;

Private string savepath;

/**

* Constructor

*

* @ Param listenport: Listener Port

* @ Param savepath: Path of the file to be saved

*

* @ Throws ioexception: An error occurred while creating the Save path.

*/

Server (INT listenport, string savepath) throws ioexception {

This. listenport = listenport;

This. savepath = savepath;

File file = new file (savepath );

If (! File. exists ()&&! File. mkdirs ()){

Throw new ioexception ("Folders cannot be created" + savepath );

}

}

// Start listening

Public void start (){

New listenthread (). Start ();

}

// The Bytes copied from the Internet are converted to int. The length of B cannot be less than 4, and only the first 4 digits will be taken.

Public static int b2i (byte [] B ){

Int value = 0;

For (INT I = 0; I <4; I ++ ){

Int shift = (4-1-I) * 8;

Value + = (B [I] & 0x000000ff) <shift;

}

Return value;

}

 

/**

* Listening thread

*/

Private class listenthread extends thread {

@ Override

Public void run (){

Try {

Serversocket Server = new serversocket (listenport );

// Start the loop

While (true ){

Socket socket = server. Accept ();

New handlethread (socket). Start ();

}

} Catch (ioexception e ){

E. printstacktrace ();

}

}

}

/**

* The thread that reads the stream and saves the file

*/

Private class handlethread extends thread {

Private Socket socket;

Private handlethread (Socket socket ){

This. Socket = socket;

}

@ Override

Public void run (){

Try {

Inputstream is = socket. getinputstream ();

Readandsave (is );

} Catch (ioexception e ){

E. printstacktrace ();

} Finally {

Try {

Socket. Close ();

} Catch (ioexception e ){

// Nothing to do

}

}

}

// Read and save the content from the stream

Private void readandsave (inputstream is) throws ioexception {

String filename = getfilename (is );

Int file_len = readinteger (is );

System. Out. println ("received file:" + filename + ", Length:" + file_len );

Readandsave0 (is, savepath + filename, file_len );

System. Out. println ("file saved successfully (" + file_len + "bytes ). ");

}

 

Private void readandsave0 (inputstream is, string path, int file_len) throws ioexception {

Fileoutputstream OS = getfileos (PATH );

Readandwrite (is, OS, file_len );

OS. Close ();

}

// Read and write simultaneously until the size is read.

Private void readandwrite (inputstream is, fileoutputstream OS, int size) throws ioexception {

Byte [] buffer = new byte [4096];

Int COUNT = 0;

While (count <size ){

Int n = is. Read (buffer );

// N =-1 is not considered here

OS. Write (buffer, 0, N );

Count + = N;

}

}

// Read the file name

Private string getfilename (inputstream is) throws ioexception {

Int name_len = readinteger (is );

Byte [] result = new byte [name_len];

Is. Read (result );

Return new string (result );

}

// Read a number

Private int readinteger (inputstream is) throws ioexception {

Byte [] bytes = new byte [4];

Is. Read (bytes );

Return b2i (bytes );

}

// Create a file and return the output stream

Private fileoutputstream getfileos (string path) throws ioexception {

File file = new file (PATH );

If (! File. exists ()){

File. createnewfile ();

}

Return new fileoutputstream (File );

}

}

}

==============================================

/**

* Sender

*/

Class client {

// Copy it online and convert int to byte

Public static byte [] i2b (int I ){

Return new byte [] {

(Byte) (I> 24) & 0xff ),

(Byte) (I> 16) & 0xff ),

(Byte) (I> 8) & 0xff ),

(Byte) (I & 0xff)

};

}

 

/**

* Send a file. File size cannot exceed {@ link integer # max_value}

*

* @ Param hostname the receiver host name or IP address

* @ Param port: receiver port number

* @ Param filepath: file path

*

* @ Throws ioexception if file reading or sending fails

*/

Public void sendfile (string hostname, int port, string filepath) throws ioexception {

File file = new file (filepath );

Fileinputstream is = new fileinputstream (filepath );

Socket socket = new socket (hostname, Port );

Outputstream OS = socket. getoutputstream ();

Try {

Int length = (INT) file. Length ();

System. Out. println ("Sending File:" + file. getname () + ", Length:" + length );

// Send the file name and content

Writefilename (file, OS );

Writefilecontent (is, OS, length );

} Finally {

OS. Close ();

Is. Close ();

}

}

// Output file content

Private void writefilecontent (inputstream is, outputstream OS, int length) throws ioexception {

// Output file length

OS. Write (i2b (length ));

// Output file content

Byte [] buffer = new byte [4096];

Int size;

While (size = is. Read (buffer ))! =-1 ){

OS. Write (buffer, 0, size );

}

}

// Output file name

Private void writefilename (File file, outputstream OS) throws ioexception {

Byte [] fn_bytes = file. getname (). getbytes ();

OS. Write (i2b (fn_bytes.length); // output file name length

OS. Write (fn_bytes); // output file name

}

}

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.