Java Socket Practice 7 use socket communication to transmit files

Source: Internet
Author: User
Tags rewind sendfile

Address: http://blog.csdn.net/kongxx/article/details/7319410

One of Java Socket practices: Single-thread Communication

Java Socket practice 2 multi-thread Communication

Java Socket 3 transmission object

Java Socket practice 4 transmission of compressed objects

Java Socket practice 5 use encryption protocol to transmit objects

Java Socket Practice 6 Use NiO package for socket communication

Previous articlesArticleThis article describes how to use socket programming to implement simple file transmission.

As the previous article introduced NiO's Application in socket, NiO packages are still used when reading and writing files.CodeIt seems a little more complicated than using the stream directly.

The following example shows that the client sends a file to the server, and the server sends a file to the client as a response. Prepare two files E:/test/server_send.log and E:/test/client. send. log File. After the test is completed, there will be two more files E:/test/server_receive.log and E:/test/client in the same directory on the client and server. receive. log File.

Next, let's take a look at the server class, focusing on the sendfile and receivefile methods.

Package COM. googlecode. garbagecan. test. socket. NIO; </P> <p> Import Java. io. file; <br/> Import Java. io. fileinputstream; <br/> Import Java. io. fileoutputstream; <br/> Import Java. io. ioexception; <br/> Import java.net. inetsocketaddress; <br/> Import Java. NIO. bytebuffer; <br/> Import Java. NIO. channels. closedchannelexception; <br/> Import Java. NIO. channels. filechannel; <br/> Import Java. NIO. channels. selectionkey; <B R/> Import Java. NIO. channels. selector; <br/> Import Java. NIO. channels. serversocketchannel; <br/> Import Java. NIO. channels. socketchannel; <br/> Import Java. util. iterator; <br/> Import Java. util. logging. level; <br/> Import Java. util. logging. logger; </P> <p> public class myserver4 {</P> <p> private final static logger = logger. getlogger (myserver4.class. getname (); </P> <p> Public static void main (string [] ARGs) {<br/> selector = NULL; <br/> serversocketchannel = NULL; </P> <p> try {<br/> // selector for incoming time requests <br/> selector = selector. open (); </P> <p> // create a new server socket and set to Non blocking mode <br/> serversocketchannel = serversocketchannel. open (); <br/> serversocketchannel. configureblocking (false); </P> <p> // bind the server socket to the local hos T and port <br/> serversocketchannel. socket (). setreuseaddress (true); <br/> serversocketchannel. socket (). BIND (New inetsocketaddress (10000); </P> <p> // register accepts on the server socket with the selector. this <br/> // step tells the selector that the socket wants to be put on the <br/> // ready list when accept operations occur, so allowing multiplexed <br/> // non-blocking I/O to take place. <br/> Se Rversocketchannel. register (selector, selectionkey. op_accept); </P> <p> // here's where everything happens. the select method will <br/> // return when any operations registered above have occurred, the <br/> // thread has been interrupted, etc. <br/> while (selector. select ()> 0) {<br/> // someone is ready for I/O, get the ready keys <br/> iterator <selectionkey> it = selector. selectedkeys (). iterator (); </ P> <p> // walk through the ready keys collection and process date requests. <br/> while (it. hasnext () {<br/> selectionkey readykey = it. next (); <br/> it. remove (); </P> <p> // The key indexes into the selector so you <br/> // can retrieve the socket that's ready for I/O <br/> doit (serversocketchannel) readykey. channel (); <br/>}< br/>} catch (closedchannelexception ex) {<br/> logger. log (level. sever E, null, ex); <br/>}catch (ioexception ex) {<br/> logger. log (level. severe, null, ex); <br/>}finally {<br/> try {<br/> selector. close (); <br/>}catch (exception ex) {}< br/> try {<br/> serversocketchannel. close (); <br/>}catch (exception ex) {}< br/>}</P> <p> Private Static void doit (final serversocketchannel) throws ioexception {<br/> socketchannel = NULL; <br /> Try {<br/> socketchannel = serversocketchannel. accept (); </P> <p> receivefile (socketchannel, new file ("E:/test/server_receive.log"); <br/> sendfile (socketchannel, new file ("E:/test/server_send.log"); <br/>}finally {<br/> try {<br/> socketchannel. close (); <br/>}catch (exception ex) {}< br/>}</P> <p> Private Static void receivefile (socketchannel, file) throws ioexception {< Br/> fileoutputstream Fos = NULL; <br/> filechannel channel = NULL; </P> <p> try {<br/> Fos = new fileoutputstream (File ); <br/> channel = FOS. getchannel (); <br/> bytebuffer buffer = bytebuffer. allocatedirect (1024); </P> <p> int size = 0; <br/> while (size = socketchannel. read (buffer ))! =-1) {<br/> buffer. flip (); <br/> If (size> 0) {<br/> buffer. limit (size); <br/> channel. write (buffer); <br/> buffer. clear (); <br/>}< br/>} finally {<br/> try {<br/> channel. close (); <br/>}catch (exception ex) {}< br/> try {<br/> FOS. close (); <br/>}catch (exception ex) {}< br/>}</P> <p> Private Static void sendfile (socketchannel, file) throws ioexception {<br/> fileinputs Tream fiis = NULL; <br/> filechannel channel = NULL; <br/> try {<br/> fiis = new fileinputstream (File); <br/> channel = fiis. getchannel (); <br/> bytebuffer buffer = bytebuffer. allocatedirect (1024); <br/> int size = 0; <br/> while (size = channel. read (buffer ))! =-1) {<br/> buffer. rewind (); <br/> buffer. limit (size); <br/> socketchannel. write (buffer); <br/> buffer. clear (); <br/>}< br/> socketchannel. socket (). shutdownoutput (); <br/>}finally {<br/> try {<br/> channel. close (); <br/>}catch (exception ex) {}< br/> try {<br/> FCM. close (); <br/>}catch (exception ex) {}< br/>}< br/>}Below is the client Program Code, but also focus on sendfile and receivefile Methods

Package COM. googlecode. garbagecan. test. socket. NIO; </P> <p> Import Java. io. file; <br/> Import Java. io. fileinputstream; <br/> Import Java. io. fileoutputstream; <br/> Import Java. io. ioexception; <br/> Import java.net. inetsocketaddress; <br/> Import java.net. socketaddress; <br/> Import Java. NIO. bytebuffer; <br/> Import Java. NIO. channels. filechannel; <br/> Import Java. NIO. channels. socketchannel; <br/> Import Java. u Til. logging. level; <br/> Import Java. util. logging. logger; </P> <p> public class myclient4 {</P> <p> private final static logger = logger. getlogger (myclient4.class. getname (); </P> <p> Public static void main (string [] ARGs) throws exception {<br/> New thread (New myrunnable ()). start (); <br/>}</P> <p> Private Static final class myrunnable implements runnable {<br/> Public void run () {<br/> socketchannel Socketchannel = NULL; <br/> try {<br/> socketchannel = socketchannel. open (); <br/> socketaddress = new inetsocketaddress ("localhost", 10000); <br/> socketchannel. connect (socketaddress); </P> <p> sendfile (socketchannel, new file ("E:/test/client_send.log"); <br/> receivefile (socketchannel, new file ("E:/test/client_receive.log"); <br/>}catch (exception ex) {<br/> logger. log (level. severe, nu Ll, ex); <br/>}finally {<br/> try {<br/> socketchannel. close (); <br/>}catch (exception ex) {}< br/>}</P> <p> private void sendfile (socketchannel, file file) throws ioexception {<br/> fileinputstream FD = NULL; <br/> filechannel channel = NULL; <br/> try {<br/> fiis = new fileinputstream (File); <br/> channel = fiis. getchannel (); <br/> bytebuffer buffer = bytebuffer. allocatedirect (102 4); <br/> int size = 0; <br/> while (size = channel. Read (buffer ))! =-1) {<br/> buffer. rewind (); <br/> buffer. limit (size); <br/> socketchannel. write (buffer); <br/> buffer. clear (); <br/>}< br/> socketchannel. socket (). shutdownoutput (); <br/>}finally {<br/> try {<br/> channel. close (); <br/>}catch (exception ex) {}< br/> try {<br/> FCM. close (); <br/>}catch (exception ex) {}< br/>}</P> <p> private void receivefile (socketchannel, file file) throws ioexcep Tion {<br/> fileoutputstream Fos = NULL; <br/> filechannel channel = NULL; </P> <p> try {<br/> Fos = new fileoutputstream (File); <br/> channel = FOS. getchannel (); <br/> bytebuffer buffer = bytebuffer. allocatedirect (1024); </P> <p> int size = 0; <br/> while (size = socketchannel. read (buffer ))! =-1) {<br/> buffer. flip (); <br/> If (size> 0) {<br/> buffer. limit (size); <br/> channel. write (buffer); <br/> buffer. clear (); <br/>}< br/>} finally {<br/> try {<br/> channel. close (); <br/>}catch (exception ex) {}< br/> try {<br/> FOS. close (); <br/>}catch (exception ex) {}< br/>}< br/>First, run the myserver4 listener, and then run the myclient4 class to send files to the server and receive the server response files. After running, check the files received by the server and the client.

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.