Java使用Socket通信传输文件的方法示例
程序员文章站
2023-12-11 19:47:28
本文实例讲述了java使用socket通信传输文件的方法。分享给大家供大家参考,具体如下:
前面几篇文章介绍了使用java的socket编程和nio包在socket中的应...
本文实例讲述了java使用socket通信传输文件的方法。分享给大家供大家参考,具体如下:
前面几篇文章介绍了使用java的socket编程和nio包在socket中的应用,这篇文章说说怎样利用socket编程来实现简单的文件传输。
这里由于前面一片文章介绍了nio在socket中的应用,所以这里在读写文件的时候也继续使用nio包,所以代码看起来会比直接使用流的方式稍微复杂一点点。
下面的示例演示了客户端向服务器端发送一个文件,服务器作为响应给客户端回发一个文件。这里准备两个文件e:/test/server_send.log和e:/test/client.send.log文件,在测试完毕后在客户端和服务器相同目录下会多出两个文件e:/test/server_receive.log和e:/test/client.receive.log文件。
下面首先来看看server类,主要关注其中的sendfile和receivefile方法。
package com.googlecode.garbagecan.test.socket.nio; import java.io.file; import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.ioexception; import java.net.inetsocketaddress; import java.nio.bytebuffer; import java.nio.channels.closedchannelexception; import java.nio.channels.filechannel; import java.nio.channels.selectionkey; import java.nio.channels.selector; import java.nio.channels.serversocketchannel; import java.nio.channels.socketchannel; import java.util.iterator; import java.util.logging.level; import java.util.logging.logger; public class myserver4 { private final static logger logger = logger.getlogger(myserver4.class.getname()); public static void main(string[] args) { selector selector = null; serversocketchannel serversocketchannel = null; try { // selector for incoming time requests selector = selector.open(); // create a new server socket and set to non blocking mode serversocketchannel = serversocketchannel.open(); serversocketchannel.configureblocking(false); // bind the server socket to the local host and port serversocketchannel.socket().setreuseaddress(true); serversocketchannel.socket().bind(new inetsocketaddress(10000)); // register accepts on the server socket with the selector. this // step tells the selector that the socket wants to be put on the // ready list when accept operations occur, so allowing multiplexed // non-blocking i/o to take place. serversocketchannel.register(selector, selectionkey.op_accept); // here's where everything happens. the select method will // return when any operations registered above have occurred, the // thread has been interrupted, etc. while (selector.select() > 0) { // someone is ready for i/o, get the ready keys iterator<selectionkey> it = selector.selectedkeys().iterator(); // walk through the ready keys collection and process date requests. while (it.hasnext()) { selectionkey readykey = it.next(); it.remove(); // the key indexes into the selector so you // can retrieve the socket that's ready for i/o doit((serversocketchannel) readykey.channel()); } } } catch (closedchannelexception ex) { logger.log(level.severe, null, ex); } catch (ioexception ex) { logger.log(level.severe, null, ex); } finally { try { selector.close(); } catch(exception ex) {} try { serversocketchannel.close(); } catch(exception ex) {} } } private static void doit(final serversocketchannel serversocketchannel) throws ioexception { socketchannel socketchannel = null; try { socketchannel = serversocketchannel.accept(); receivefile(socketchannel, new file("e:/test/server_receive.log")); sendfile(socketchannel, new file("e:/test/server_send.log")); } finally { try { socketchannel.close(); } catch(exception ex) {} } } private static void receivefile(socketchannel socketchannel, file file) throws ioexception { fileoutputstream fos = null; filechannel channel = null; try { fos = new fileoutputstream(file); channel = fos.getchannel(); bytebuffer buffer = bytebuffer.allocatedirect(1024); int size = 0; while ((size = socketchannel.read(buffer)) != -1) { buffer.flip(); if (size > 0) { buffer.limit(size); channel.write(buffer); buffer.clear(); } } } finally { try { channel.close(); } catch(exception ex) {} try { fos.close(); } catch(exception ex) {} } } private static void sendfile(socketchannel socketchannel, file file) throws ioexception { fileinputstream fis = null; filechannel channel = null; try { fis = new fileinputstream(file); channel = fis.getchannel(); bytebuffer buffer = bytebuffer.allocatedirect(1024); int size = 0; while ((size = channel.read(buffer)) != -1) { buffer.rewind(); buffer.limit(size); socketchannel.write(buffer); buffer.clear(); } socketchannel.socket().shutdownoutput(); } finally { try { channel.close(); } catch(exception ex) {} try { fis.close(); } catch(exception ex) {} } } }
下面是client程序代码,也主要关注sendfile和receivefile方法
package com.googlecode.garbagecan.test.socket.nio; import java.io.file; import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.ioexception; import java.net.inetsocketaddress; import java.net.socketaddress; import java.nio.bytebuffer; import java.nio.channels.filechannel; import java.nio.channels.socketchannel; import java.util.logging.level; import java.util.logging.logger; public class myclient4 { private final static logger logger = logger.getlogger(myclient4.class.getname()); public static void main(string[] args) throws exception { new thread(new myrunnable()).start(); } private static final class myrunnable implements runnable { public void run() { socketchannel socketchannel = null; try { socketchannel = socketchannel.open(); socketaddress socketaddress = new inetsocketaddress("localhost", 10000); socketchannel.connect(socketaddress); sendfile(socketchannel, new file("e:/test/client_send.log")); receivefile(socketchannel, new file("e:/test/client_receive.log")); } catch (exception ex) { logger.log(level.severe, null, ex); } finally { try { socketchannel.close(); } catch(exception ex) {} } } private void sendfile(socketchannel socketchannel, file file) throws ioexception { fileinputstream fis = null; filechannel channel = null; try { fis = new fileinputstream(file); channel = fis.getchannel(); bytebuffer buffer = bytebuffer.allocatedirect(1024); int size = 0; while ((size = channel.read(buffer)) != -1) { buffer.rewind(); buffer.limit(size); socketchannel.write(buffer); buffer.clear(); } socketchannel.socket().shutdownoutput(); } finally { try { channel.close(); } catch(exception ex) {} try { fis.close(); } catch(exception ex) {} } } private void receivefile(socketchannel socketchannel, file file) throws ioexception { fileoutputstream fos = null; filechannel channel = null; try { fos = new fileoutputstream(file); channel = fos.getchannel(); bytebuffer buffer = bytebuffer.allocatedirect(1024); int size = 0; while ((size = socketchannel.read(buffer)) != -1) { buffer.flip(); if (size > 0) { buffer.limit(size); channel.write(buffer); buffer.clear(); } } } finally { try { channel.close(); } catch(exception ex) {} try { fos.close(); } catch(exception ex) {} } } } }
首先运行myserver4类启动监听,然后运行myclient4类来向服务器发送文件以及接受服务器响应文件。运行完后,分别检查服务器和客户端接收到的文件。
更多关于java相关内容感兴趣的读者可查看本站专题:《java socket编程技巧总结》、《java文件与目录操作技巧汇总》、《java数据结构与算法教程》、《java操作dom节点技巧总结》和《java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。