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. Web自动化测试:xpath & CSS Selector定位

    Xpath 和 CSS Selector简介 CSS Selector CSS Selector和Xpath都可以用来表示XML文档中的位置.CSS (Cascading Style Sheets)是 ...

  2. day113:MoFang:种植园商城页面&充值集成Alipay完成支付的准备工作

    目录 1.种植园商城页面初始化 2.规划商品种类并且构建关于商品的模型类 3.解决APP打包编译之后的跨域限制 4.商品列表后端接口实现 5.前端获取商品列表并显示 6.种植园点击充值允许用户选择充值 ...

  3. MRP物料需求计划

    1.重订货点的采购计划. 计算方式:再订货点的库存数量 = 安全库存 + 采购提前期 * 每天消耗的数量 一旦库存数量触及再订货点的库存数量,需触发采购订单订购物料,理想的情况下 ,下次到采购订单收货 ...

  4. Docker安装系列教程

    首先准备一台Centos7版本的虚拟机,它支持docker容器技术.本案例使用centos7虚拟机安装docker容器. 一.安装 1.启动虚拟机,配置虚拟机能够访问互联网 2. 安装支持软件包,提供 ...

  5. Turtlebot3新手教程:Open-Manipulator机械臂

    *本文针对如何结合turtlebot3和Open-Manipulator机械臂做出讲解 测试在Ubuntu 16.04, Linux Mint 18.1和ROS Kinetic Kame下进行 具体步 ...

  6. Eclipse 使用svn时出现 “Previous operation has not finished; run 'cleanup' if it was interrupted“问题

    在执行svn操作的时候出现了下面的问题 commit -m "" E:/eclipse/workplace/BRobotAPP/blockly/googleDemo/blockly ...

  7. 第9章 集合处理(数组、Map、Set)

    目录 1. 数组 1.1 创建数组 1.2 在数组两端添加删除元素 1.3 在数组任意位置添加.删除元素 delete删除数组元素无效 使用splice方法增.删.改元素 1.4 数组的常用操作 数组 ...

  8. uni-app阻止事件向父级冒泡

    在官网找到的就只有这个方法,但是我放在app项目里并不支持,所以就想到vue的阻止事件冒泡的方法,现在分享,免得大家踩坑     <view class="parent" @ ...

  9. 基于腾讯云存储COS的ClickHouse数据冷热分层方案

    一.ClickHouse简介 ClickHouse是一个用于联机分析(OLAP)的列式数据库管理系统(DBMS),支持PB级数据量的交互式分析,ClickHouse最初是为YandexMetrica ...

  10. 剑指offer-查找数组中重复的数字

    找出数组中重复的数字. 在一个长度为 n 的数组 nums 里的所有数字都在 0-n-1 的范围内.数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次.请找出数组中任意一个重 ...