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

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

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) {}
}
}
}
}

Java Socket实战之七 使用Socket通信传输文件的更多相关文章

  1. java socket通信-传输文件图片--传输图片

    ClientTcpSend.java   client发送类 package com.yjf.test; import java.io.DataOutputStream; import java.io ...

  2. 在java中使用SFTP协议安全的传输文件

    本文介绍在Java中如何使用基于SSH的文件传输协议(SFTP)将文件从本地上传到远程服务器,或者将文件在两个服务器之间安全的传输.我们先来了解一下这几个协议 SSH 是较可靠,专为远程登录会话和其他 ...

  3. Java Socket实战之一:单线程通信

    转自:http://developer.51cto.com/art/201202/317543.htm 现在做Java直接使用Socket的情况是越来越少,因为有很多的选择可选,比如说可以用sprin ...

  4. 98.TCP通信传输文件

    客户端 #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include <stdlib.h> #include <s ...

  5. C#串口通信—传输文件测试

    说明:该程序可能不具备实用性,仅测试用. 一.使用虚拟串口工具VSPD虚拟两个串口COM1和COM2 二.约定 占一个字节,代码如下: using System; using System.Colle ...

  6. Android网络编程只局域网传输文件

    Android网络编程之局域网传输文件: 首先创建一个socket管理类,该类是传输文件的核心类,主要用来发送文件和接收文件 具体代码如下: package com.jiao.filesend; im ...

  7. Java Socket实战之三:传输对象

    转自:https://i.cnblogs.com/EditPosts.aspx?opt=1 前面两篇文章介绍了怎样建立Java Socket通信,这一篇说一下怎样使用Java Socket来传输对象. ...

  8. Java Socket实战之三 传输对象

    首先需要一个普通的对象类,由于需要序列化这个对象以便在网络上传输,所以实现java.io.Serializable接口就是必不可少的了,入下: public class User implements ...

  9. Java Socket实战之五:使用加密协议传输对象

    转自:http://developer.51cto.com/art/201202/317547.htm 前面几篇博文提到了Socket中一些常用的用法,但是对于一些有安全要求的应用就需要加密传输的数据 ...

随机推荐

  1. (三)、vim的移动(旋转,跳跃)

    一.以word为单位的移动 1.w 向后移动到后一个单词词头,取自"word" This is a line with example text ----->--->- ...

  2. JS实现JSON数组合并和去重

    var a=[{"id":"1001","name":"张三","age":"18&quo ...

  3. 在jsp页面动态添加,删除文本框模块

    jsp代码============ <table class="crud-content-info" > <tr > <td align=" ...

  4. java零基础之--JDK安装篇

    ---恢复内容开始--- 很多零基础学习者在开始学习java中很难理解JDK的安装和配置,以下是基于Windows 7 的安装配置流程(Windows 10类似) 1. 在安装之前我们先了解几个名词: ...

  5. python的22个基本语法

    "人生苦短,我用Python".Python编程语言是最容易学习.并且功能强大的语言.只需会微信聊天.懂一点英文单词即可学会Python编程语言.但是很多人声称自己精通Python ...

  6. 【Go】四舍五入在go语言中为何如此困难

    四舍五入是一个非常常见的功能,在流行语言标准库中往往存在 Round 的功能,它最少支持常用的 Round half up 算法. 而在 Go 语言中这似乎成为了难题,在 stackoverflow ...

  7. 每日一个linux命令6 -- rmdir

    rmdir doc 如果doc为空目录则删除,否则无法删除. rmdir -p test2/test3 递归删除空目录,首先判断test3,如果test3为空,则删除test3,此时判断test2,如 ...

  8. Oracle RedoLog-二进制格式分析,文件头,DML,DDL

    上篇文章,简单介绍了 RedoLog 是什么,以及怎么从 Oracle Dump 二进制日志.接下来,分析下 Redo Log 二进制文件的格式,主要包括:文件头,重做日志头,DML-INSERT 操 ...

  9. NAT模式/路由模式/全路由模式 (转)

    route全路由NAT NAT模式.此模式下,由局域网向广域网发送的数据包默认经过NAT转换,但路由器对所有源地址与局域网接口不在同一网段的数据包均不进行处理.例如,路由器LAN口IP设置为192.1 ...

  10. Lesson_strange_words5

    certain 一些 the company's 公司的 implement 实现 plane 平面 sluggishly 迟缓地,缓慢地 frustrated 懊恼的 profiler 分析器,分析 ...