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. 构建Zookeeper集群(zkcluster) ~一篇文章玩转zk集群^.^

    概念 Zookeeper集群是由一个leader(负责人)主机和多个follower(追随者)或observer(观察者)主机组成. 构建一个Zookeeper集群需要有一个leader和一个foll ...

  2. [leetcode]297. Serialize and Deserialize Binary Tree一般二叉树的编解码

    由于一般的前序遍历不能唯一的还原出原本你的二叉树,所以要改变一下: 记录二叉树的结构信息,也就是空节点用符号表示 一般的前序遍历只是记录了节点的前后顺序,通过记录空节点,每一层的结构就可以记录下来 解 ...

  3. ESP8266-01烧录神器,ESP8266-01S烧录程序 ESP-01烧录固件

    如下图所示:"USB转ESP8266",在某宝上可以买到,但是建议买两个! 为什么要买两个呢?一个用于测试AT指令.接电呀什么的.另外一个通过焊接就可以改造成烧录器了. 引脚说明: ...

  4. Hadoop之WordCount

    求平均数是MapReduce比较常见的算法,求平均数的算法也比较简单,一种思路是Map端读取数据,在数据输入到Reduce之前先经过shuffle,将map函数输出的key值相同的所有的value值形 ...

  5. Redis的内存淘汰

    Redis占用内存大小 我们知道Redis是基于内存的key-value数据库,因为系统的内存大小有限,所以我们在使用Redis的时候可以配置Redis能使用的最大的内存大小. 1.通过配置文件配置 ...

  6. 第13章节 BJROBOT 雷达跟随【ROS全开源阿克曼转向智能网联无人驾驶车】

    雷达跟随说明:注意深度摄像头的 USB 延长线,可能会对雷达扫描造成影响, 所以在雷达跟随前,把深度摄像头的 USB 延长线取下.另外雷达跟随范围大概是前方 50cm 和 120°内扫描到的物体都可以 ...

  7. MyArray框架搭建与实现

    #include<iostream> using namespace std; template<class T> class MyArray { public: //构造函数 ...

  8. 上班从换一张桌面壁纸开始——开源小工具Bing每日壁纸

    发布一个自用的开源小软件,Bing每日壁纸,使用c# winform开发.该小软件可以自动获取Bing的精美图片设置为壁纸,并且支持随机切换历史壁纸,查看壁纸故事. 功能特性 自动获取Bing最新图片 ...

  9. 认识webservice

    1.为什么需要webservice? 目前还有很多商用程序继续在使用C++.Java.Visual Basic和其他各种各样的语言编写.现在,除了最简单的程序之外,所有的应用程序都需要与运行在其他异构 ...

  10. 详细的String源码解析

    我们常常把String类型的字符串作为HashMap的key,为什么要这样做呢? 因为String是不可变的,一旦初始化就不再改变了,如果被修改将会是一个新对象. @Test public void ...