Java Socket实战之七 使用Socket通信传输文件
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通信传输文件的更多相关文章
- java socket通信-传输文件图片--传输图片
ClientTcpSend.java client发送类 package com.yjf.test; import java.io.DataOutputStream; import java.io ...
- 在java中使用SFTP协议安全的传输文件
本文介绍在Java中如何使用基于SSH的文件传输协议(SFTP)将文件从本地上传到远程服务器,或者将文件在两个服务器之间安全的传输.我们先来了解一下这几个协议 SSH 是较可靠,专为远程登录会话和其他 ...
- Java Socket实战之一:单线程通信
转自:http://developer.51cto.com/art/201202/317543.htm 现在做Java直接使用Socket的情况是越来越少,因为有很多的选择可选,比如说可以用sprin ...
- 98.TCP通信传输文件
客户端 #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include <stdlib.h> #include <s ...
- C#串口通信—传输文件测试
说明:该程序可能不具备实用性,仅测试用. 一.使用虚拟串口工具VSPD虚拟两个串口COM1和COM2 二.约定 占一个字节,代码如下: using System; using System.Colle ...
- Android网络编程只局域网传输文件
Android网络编程之局域网传输文件: 首先创建一个socket管理类,该类是传输文件的核心类,主要用来发送文件和接收文件 具体代码如下: package com.jiao.filesend; im ...
- Java Socket实战之三:传输对象
转自:https://i.cnblogs.com/EditPosts.aspx?opt=1 前面两篇文章介绍了怎样建立Java Socket通信,这一篇说一下怎样使用Java Socket来传输对象. ...
- Java Socket实战之三 传输对象
首先需要一个普通的对象类,由于需要序列化这个对象以便在网络上传输,所以实现java.io.Serializable接口就是必不可少的了,入下: public class User implements ...
- Java Socket实战之五:使用加密协议传输对象
转自:http://developer.51cto.com/art/201202/317547.htm 前面几篇博文提到了Socket中一些常用的用法,但是对于一些有安全要求的应用就需要加密传输的数据 ...
随机推荐
- 漫画 | 老泪纵横,约会也不敢耽误改bug
啥都不说了, 直接看图, 就说你中了几枪. 小莱已经抹了好几把辛酸泪-- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 关于作者 作者:大家好,我是莱乌,BAT搬砖工一枚.从 ...
- iOS崩溃治理--开篇
去年我开始负责iOS崩溃治理的工作,从原来的万分之五崩溃率,一直到现在的万分之一左右的崩溃率,期间踩了很多坑,因此想和大家分享一下,希望能对大家有所帮助,也欢迎大家私信交流. 如果你打算开始治理崩溃的 ...
- 10天,从.Net转Java,并找到月薪2W的工作(一)
大学学的是Java,但是工作一直都是.Net方面的工作. 看到各种各样的大厂都是招Java,工资比.Net高,岗位多.而.Net大多都是维护老系统,传统行业这类的工作.甚至发现工作经验不足我一半的薪水 ...
- mysql 提示 vcruntime140_1.dll丢失
百度网盘:https://pan.baidu.com/s/1vbVexHs1eRfGlnTbr8U53Q 提取码:59tm 将两个文件同时放到路径:C:\Windows\System32 下,运行ba ...
- [LeetCode]92. Reverse Linked List II反转部分链表
/* 重点还是反转链表 思路就是中间的反转,然后两头接上 */ public ListNode reverseBetween(ListNode head, int m, int n) { if (he ...
- [leetcode]380. Insert Delete GetRandom O(1)设计数据结构,实现存,删,随机取的时间复杂度为O(1)
题目: Design a data structure that supports all following operations in average O(1) time.1.insert(val ...
- hadoop伪分布式平台组件搭建
第一部分:系统基础配置 系统基础配置中主完成了安装大数据环境之前的基础配置,如防火墙配置和安装MySQL.JDK安装等 第一步:关闭防火墙 Hadoop与其他组件的服务需要通过端口进行通信,防火墙的存 ...
- Erlang那些事儿第3回之我是函数(fun),万物之源MFA
Erlang代码到处都是模式匹配,这把屠龙刀可是Erlang的看家本领.独家绝学,之前在<Erlang那些事儿第1回之我是变量,一次赋值永不改变>文章提到过,Erlang一切皆是模式匹配. ...
- druid监控
1 @ConfigurationProperties(prefix = "spring.datasource") 2 @Bean 3 public DataSource druid ...
- slice,splice,split,unshift的用法
工作了很久始终对这4个用法处于混淆状态,今天写个帖子来警示下自己 // slice(start,end),从start值开始截取到end前的元素组成新的数组,不改变原数组 // slice(index ...