Java Socket for file transfer 2

Source: Internet
Author: User
Tags sendfile

Package fileinsockettraslation;
/*
* The Helper port used in this class is initially set to 10000. If the binding fails, try another port.
* The trybindtimes table is used to identify the number of bindings. If the Help fails, it will be added.
* The current help port is determined by defaultbindport + trybindtimes.
* The external system (the object that calls this program) can obtain the current helper port.
* Notify the client service port so that it can be correctly connected to the port.
*/

Import java.net .*;
Import java. Io .*;

Import javax. Swing. jfilechooser;
Import javax. Swing. joptionpane;
Public class GetFile extends thread {

Serversocket sersocket; // The service socket waits for the peer connection and file sending.
Socket tempsocket; // The socket generated by the Service socket
Inputstream insocket; // used for reading

Randomaccessfile infile = NULL; // random File Access
Byte bytebuffer [] = new byte [1024]; // temporary easing Area


Int defaultbindport = 10000; // port 10000 is used by default to listen for requests.
Int trybindtimes = 0; // the initial number of ports bound is 0.
Int currentbindport = defaultbindport + trybindtimes; // The currently bound port number is the default port 10000.

Private void bindtoserverport () throws exception // The exception is thrown because the service port cannot be bound.
{
Try {
System. Out. println ("try to bind the port number:" + this. currentbindport); // output the bound port number to the current console.
Sersocket = new serversocket (this. currentbindport); // open a service socket on your machine and wait for the sender to connect

} Catch (exception e ){
E. printstacktrace ();

System. Out. println (E. tostring (); // retry if the binding fails.

This. trybindtimes = This. trybindtimes + 1; // you have tried gettrybindedtimes more than once.
This. currentbindport = This. defaultbindport + this. trybindtimes ;//
If (this. trybindtimes> = 20)
{
Throw new exception ("cannot be bound to the specified port" + '\ n' + "tried too many times! ");
// Exit if the number of attempts exceeds 20
}
This. bindtoserverport (); // recursive binding
}
System. Out. println ("successfully bound port:" + this. currentbindport); // output the bound port number to the current console.

}
Public int gettrybindedtimes ()
{
Return this. trybindtimes;
}
Public int getcurrentbindingport ()
{
Return this. currentbindport;
}
************************** *******************
Public static void main (string ARGs []) {
GetFile gf = NULL;
Try {
GF = new getfiles (10000 );
} Catch (exception e ){
E. printstacktrace ();
System. Out. println ("file cannot be transferred! ");
System. Exit (1 );
}
GF. Start ();

}
************************** *******************

Public GetFile (INT port) throws exception // The exception is thrown because the service port cannot be bound.
{
Try {

This. bindtoserverport (); // bind the service port


} Catch (exception e ){
E. printstacktrace ();
System. Out. println (E. tostring (); // retry if the binding fails.
Throw new exception ("port binding failed! ");

}
Jfilechooser jfc = new jfilechooser ("."); // The file selector is opened in the current directory.
Jfc. showsavedialog (New javax. Swing. jframe ());
File savedfile = jfc. getselectedfile (); // obtain the current selected file reference

If (savedfile! = NULL) // select a file
{
Infile = new randomaccessfile (savedfile, "RW"); // the random access file used to read data can read data in blocks each time.
}
}

Public void run (){
Try {
If (this. infile = NULL)
{
System. Out. println ("no file selected ");
This. sersocket. Close (); // close the service provider socket
Return; // No file selected
}
System. Out. println ("wait for..." + '\ n' + "waiting for peer access ");
Tempsocket = sersocket. Accept (); // wait for the peer connection
This. sersocket. setsotimeout (5000); // an exception will be thrown if the connection fails for five seconds.
This. insocket = tempsocket. getinputstream (); // gets the input stream
} Catch (exception ex ){
System. Out. println (ex. tostring ());
Ex. printstacktrace ();
Return;
}

Int amount; // The following is the file transfer code and stream socket cleanup.
Try {
While (amount = insocket. Read (bytebuffer ))! =-1 ){
Infile. Write (bytebuffer, 0, amount );
}

Insocket. Close (); // close the stream
Javax. Swing. joptionpane. showmessagedialog (New javax. Swing. jframe (), "received successfully", "prompt! ",
Javax. Swing. joptionpane. plain_message );
System. Out. println ("Get OK ");
System. Out. println ("received! ");
Infile. Close (); // close the file
Tempsocket. Close (); // close the temporary socket
This. sersocket. Close (); // close the service provider socket
} Catch (ioexception e ){
System. Out. println (E. tostring ());
E. printstacktrace ();
}



}


}

Package fileinsockettraslation;

Import java.net .*;
Import java. Io .*;
/* When the server is enabled
* Instantiate a socket
* And send the file
*
*
**/
Import javax. Swing. jfilechooser;
Public class sendfile extends thread {
String remoteipstring = NULL; // Remote String
Int port; // remote service port
Socket tempsocket; // temporary socket
Outputstream outsocket; // output stream used to send files
Randomaccessfile OUTFILE; // file to be sent
Byte bytebuffer [] = new byte [1024]; // temporary cache for sending files


**************************** ****************************
Public static void main (string ARGs []) {
Sendfile Sf = new sendfile ("127.0.0.1", 10000 );
SF. Start ();

}
**************************** ****************************

Public sendfile (string remoteipstring, int port) {// The constructor is only used to select the location of the file to be sent and receive remote addresses and ports from outside
Try {
This. remoteipstring = remoteipstring;
This. Port = port;

// % Select the file location to be sent % %
Jfilechooser jfc = new jfilechooser (".");
File file = NULL;
Int returnval = jfc. showopendialog (New javax. Swing. jframe ());
If (returnval = jfilechooser. approve_option)
{
File = jfc. getselectedfile ();


}
// % %

OUTFILE = new randomaccessfile (file, "R ");



} Catch (exception e ){}
}

Public void run (){
Try {
// The prerequisite is that the server must be enabled first.
This. tempsocket = new socket (this. remoteipstring, this. Port );
System. Out. println ("successfully connected to the server ");
Outsocket = tempsocket. getoutputstream ();

Int amount;
System. Out. println ("start sending files ");
While (amount = OUTFILE. Read (bytebuffer ))! =-1 ){
Outsocket. Write (bytebuffer, 0, amount );
}
System. Out. println ("Send File complete ");
Javax. Swing. joptionpane. showmessagedialog (New javax. Swing. jframe (), "sent", "prompt! ",
Javax. Swing. joptionpane. plain_message );
OUTFILE. Close ();
Tempsocket. Close ();

} Catch (ioexception e ){
System. Out. println (E. tostring ());
E. printstacktrace ();
}


}
}

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.