- 浏览: 496016 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (301)
- Swing技术 (1)
- Linux (1)
- Javascript (22)
- 数据结构和算法 (3)
- J2SE (36)
- workflow (5)
- 设计模式 (14)
- web service (19)
- Ajax (14)
- 中间件 & 服务器 (8)
- 多线程 (9)
- Oracle (52)
- sys & soft (10)
- JMS (3)
- sso (9)
- android (11)
- struts2 (10)
- web协议 (2)
- 分布式 (2)
- PM (2)
- OLAP (3)
- Redis (2)
- Hibernate (7)
- ibatis (2)
- SQLServer (1)
- maven (3)
- Spring (7)
- Jsp (2)
- slf4j (1)
- jQuery (15)
- 权限 (1)
- 系统集成 (1)
- 笔记 (1)
- Freemarker (2)
- 项目管理 (1)
- eclipse (3)
- GIS (1)
- NoSql (3)
- win10 (1)
- win10网络 (2)
- 底层 (3)
- 数据库 (0)
最新评论
-
kabuto_v:
请问那种图,uml图是怎么画出来的呢?是您自己手工画的,还是有 ...
FastJSON 序列化、反序列化实现 -
梦行Monxin商城系统:
电商实例、业务并发、网站并发及解决方法 -
rockethj8:
client 㓟有一个参数是可以忽略一些URL 不进行验证登录 ...
SSO 之 (单点登录)实施中遇到的几个问题 -
mengxiangfeiyan:
好啊。。。。。
Oracle删除表,删除数据以及恢复数据、利用现有表创建新表
http://blog.csdn.net/kongxx/article/details/7319410
前面几篇文章介绍了使用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方法。
[java] view plaincopyprint?
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方法
[java] view plaincopyprint?
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的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方法。
[java] view plaincopyprint?
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方法
[java] view plaincopyprint?
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类来向服务器发送文件以及接受服务器响应文件。运行完后,分别检查服务器和客户端接收到的文件
发表评论
-
底层读写-NIO实战
2016-03-04 10:51 829最近参与实现底层高并发处理的项目,接收socket ... -
底层网络读写
2016-03-04 10:49 568Java NIO:NIO概述 http://w ... -
java方法返回多个值
2016-01-22 09:11 764http://www.iteye.com/topic/114 ... -
模拟form表单上传图片
2016-01-19 17:23 752转自:http://blog.csdn.net/5iasp ... -
java包装类的几点注意
2016-01-18 10:52 798java中8种基本类型变量对应的包装类: ... -
JAVA调用聚合天气api接口示例
2016-01-15 09:42 4034http://www.iteye.com/topic/114 ... -
java对象序列化过程
2016-01-05 10:22 737一、 http://bbs.csdn.net/topi ... -
Java6 枚举常见7种用法
2014-02-09 23:02 850http://blog.csdn.net/shimiso/a ... -
异常 之 异常体系
2013-10-07 23:00 899J2EE系统异常的处理准则 ... -
异常 之 finally的特殊处理
2013-10-07 22:26 908http://java.chinaitlab.com/expe ... -
Java图片剪裁功能实现
2013-07-28 23:17 1501http://shensy.iteye.com/blog/16 ... -
让frameset居中
2013-07-25 19:59 0JSPHTML 平常我个人开发页面时,一般用width ... -
session生命周期
2013-07-23 08:40 0http://blog.sina.com.cn/s/blog_ ... -
转发和重定向的区别
2013-07-23 08:30 0http://www.2cto.com/kf/201107/9 ... -
NIO 之 BIO和NIO机制和socket
2013-07-14 18:38 1412https://www.ibm.com/developerwo ... -
win7下安装配置tomcat,java运行环境
2013-06-30 19:39 0http://www.cnblogs.com/pannysp/ ... -
JSP之 操作Cookie
2013-06-12 18:09 0Cookie应该是一 ... -
Socket实战之二 多线程通信
2013-05-31 15:15 0http://blog.csdn.net/kongxx/art ... -
Socket实战之六 使用NIO包实现Socket通信
2013-05-31 15:06 1153本文地址:http://blog.csdn.net/kongx ... -
Socket实战之五 使用加密协议传输对象
2013-05-31 15:01 1293http://blog.csdn.net/kongxx/art ...
相关推荐
总结起来,Linux下的C++实现Socket文件传输涉及了Socket接口的使用、文件的读写操作,以及网络通信的多个环节。理解并熟练掌握这些知识点对于进行网络编程和开发高效率的网络应用至关重要。通过分析`fileserver.cpp`...
本项目“基于socket的文件传输”是针对Java Socket编程的一次实战练习,旨在实现单方文件的传输功能。在这个过程中,我们将深入探讨Socket编程的核心概念、步骤以及如何应用它们来实现文件的网络传输。 Socket,...
我们将结合"Java Socket实战之二 多线程通信"这篇博文进行深入解析。 首先,了解Socket的基本概念。Socket在计算机网络中扮演着客户端与服务器之间通信的桥梁角色。它提供了低级别的、面向连接的、基于TCP/IP协议的...
在IT领域,Linux Socket编程是网络通信的核心技术之一,它为开发者提供了在Linux操作系统上实现进程间通信(IPC)和网络通信的接口。本实战指南将深入探讨这一主题,帮助你掌握如何在Linux环境中构建高效的网络应用...
Linux Socket实战编程是深入理解网络通信机制的重要领域,尤其对于从事服务器端开发或者网络编程的IT专业人士来说,它是必备技能之一。本资源包含了Linux Socket实战编程的PDF文档以及配套源码,旨在帮助开发者通过...
在安卓中使用Socket通信时,可能会遇到以下问题: 1. 权限问题:安卓应用需要在AndroidManifest.xml中添加INTERNET权限,否则无法进行网络操作。 2. 网络安全性:由于Socket通信涉及数据安全,需要考虑加密措施,如...
Socket服务端、客户端通信是网络编程中...总的来说,这个项目提供了C#中Socket通信的实战示例,涵盖了服务端监听、客户端连接、数据传输以及处理多客户端连接等关键知识点,对于学习和理解网络编程具有很高的参考价值。
在Android应用开发中,手机客户端与服务器之间的通信是至关重要的,而Socket通信提供了一种可靠的、基于连接的数据传输方式。本文将深入探讨Android客户端如何利用Socket进行与服务器的交互。 一、Socket基础知识 ...
Linux Socket编程是网络编程的重要组成部分,它为开发者提供...通过这个实战教程,开发者将学习如何在Linux环境中创建和管理Socket,实现网络通信功能,这对于开发服务器应用、网络工具或分布式系统是至关重要的技能。
《实战Linux Socket编程》是关于网络编程领域的一本经典书籍,专注于Linux系统下的socket接口使用。这本书通过实例展示了如何在Linux环境下进行网络通信,涵盖了从基础的socket创建、连接到高级的多线程、多进程并发...
6. **关闭Socket**:完成通信后,使用`close()`函数关闭Socket。 在多客户端场景下,服务器需要能够同时处理多个并发的客户端连接。Linux Socket通过“复用”和“非阻塞”两种策略来实现这一点: - **复用...
总的来说,OpenCV与Socket结合实现视频传输是一个典型的跨学科应用场景,既需要理解计算机视觉的基本原理,也要掌握网络通信和Socket编程。这个项目为学习者提供了一个很好的实战平台,加深了对这两方面知识的理解和...
5. **连接Socket**:客户端使用`connect()`函数尝试连接到服务器的指定地址和端口。 6. **读写数据**:`read()`和`write()`函数分别用于从Socket读取数据和向Socket写入数据。 除了基础的Socket操作,还要了解套接...
Socket服务端实战主要涉及到网络编程的核心概念,尤其是TCP/IP协议栈中的应用层部分。Socket是计算机网络中进程间通信的一种方式,它允许不同设备上的应用程序通过网络交换数据。本实战项目将教你如何创建一个能够...
本实战教程将通过具体的源码实例,帮助你深入理解Linux Socket编程的核心概念和技巧。 一、Socket基础知识 Socket是网络通信的基础,它分为服务器端Socket和客户端Socket。服务器端Socket监听特定端口,等待客户端...
基于Python的Socket编程实战涉及创建网络应用程序,利用Python内置的socket库实现客户端和服务器之间的通信。Socket编程是一种低级网络编程技术,用于在网络上进行数据传输,支持多种协议,包括TCP和UDP。 首先,...
### 实战Linux Socket编程知识点概览 #### 一、Socket编程基础 **1.1 Socket概念简介** Socket是一种用于进程间通信的机制,它为不同主机间的进程提供了一种可靠的双向通信链路。在Linux环境下,Socket编程是实现...
在实际应用中,Socket编程常用于实现服务器端(如Web服务器、FTP服务器等)和客户端(如浏览器、文件上传工具等)的通信。此外,还广泛应用于设备间的通信,如智能家居系统、物联网设备等。 为了调试和优化Socket...
Linux Socket编程是构建网络应用程序的基础,它为进程间通信提供了接口,特别适用于网络环境中的数据交换。本资源“实战Linux Socket编程”旨在帮助你深入理解并掌握这一关键技能,尤其对于那些希望在嵌入式领域有所...