- 浏览: 984397 次
文章分类
- 全部博客 (428)
- Hadoop (2)
- HBase (1)
- ELK (1)
- ActiveMQ (13)
- Kafka (5)
- Redis (14)
- Dubbo (1)
- Memcached (5)
- Netty (56)
- Mina (34)
- NIO (51)
- JUC (53)
- Spring (13)
- Mybatis (17)
- MySQL (21)
- JDBC (12)
- C3P0 (5)
- Tomcat (13)
- SLF4J-log4j (9)
- P6Spy (4)
- Quartz (12)
- Zabbix (7)
- JAVA (9)
- Linux (15)
- HTML (9)
- Lucene (0)
- JS (2)
- WebService (1)
- Maven (4)
- Oracle&MSSQL (14)
- iText (11)
- Development Tools (8)
- UTILS (4)
- LIFE (8)
最新评论
-
Donald_Draper:
Donald_Draper 写道刘落落cici 写道能给我发一 ...
DatagramChannelImpl 解析三(多播) -
Donald_Draper:
刘落落cici 写道能给我发一份这个类的源码吗Datagram ...
DatagramChannelImpl 解析三(多播) -
lyfyouyun:
请问楼主,执行消息发送的时候,报错:Transport sch ...
ActiveMQ连接工厂、连接详解 -
ezlhq:
关于 PollArrayWrapper 状态含义猜测:参考 S ...
WindowsSelectorImpl解析一(FdMap,PollArrayWrapper) -
flyfeifei66:
打算使用xmemcache作为memcache的客户端,由于x ...
Memcached分布式客户端(Xmemcached)
DatagramChannelImpl 解析一(初始化):http://donald-draper.iteye.com/blog/2373245
DatagramChannelImpl 解析二(报文发送与接收):http://donald-draper.iteye.com/blog/2373281
DatagramChannelImpl 解析三(多播):http://donald-draper.iteye.com/blog/2373507
DatagramChannelImpl 解析四(地址绑定,关闭通道等):http://donald-draper.iteye.com/blog/2373519
前面讲过nio tcp通信,今天来看一下udp;
Server-peer
Client-peer
先启动Server-peer,后启动Client-peer,控制台输出:
Server-peer:
=========The Server is start!===========
client ip and port:192.168.31.153,10001
message come from client:Hello Server!
Client-peer:
===========The Client is start!===========
server ip and port:192.168.31.153,10000
message come from server:Hello client!
上面的报文通道使用实例用的是send和receive方法发送和接收报文,是不需要提前建立连接的。
我们看用read和write方法发送和接收报文
Server-peer:
Client-peer:
先启动Server-peer,后启动Client-peer,控制台输出:
Server-peer:
=========The Server is start!===========
is Connected:true
client ip and port:192.168.31.153,10001
message come from client:Hello Server!
Client-peer:
client send message to server is done!
===========The Client is start!===========
is Connected:true
server ip and port:192.168.31.153,10000
message come from server:Hello client!
总结:
send和receive方法发送和接收报文,是不需要提前建立连接的,而read和write方法,
是要建立连接的与SocketChannel相同。建议用send和receive方法发送和接收报文。
DatagramChannelImpl 解析二(报文发送与接收):http://donald-draper.iteye.com/blog/2373281
DatagramChannelImpl 解析三(多播):http://donald-draper.iteye.com/blog/2373507
DatagramChannelImpl 解析四(地址绑定,关闭通道等):http://donald-draper.iteye.com/blog/2373519
前面讲过nio tcp通信,今天来看一下udp;
Server-peer
package nio.datagramchannel; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.Iterator; /** * Sever * @author donald * 2017年4月11日 * 下午9:24:03 */ public class DatagramChannelServer { //manager the channel private Selector selector; /** * stat Server * @param args * @throws IOException */ public static void main(String[] args) throws IOException{ DatagramChannelServer server = new DatagramChannelServer(); server.initServer("192.168.31.153", 10000); server.listen(); } /** * get the ServerSocket and finish some initial work * @param port * @throws IOException */ public void initServer(String host, int port) throws IOException{ //get the ServerSocket DatagramChannel serverChannel = DatagramChannel.open(); // set no blocking mode serverChannel.configureBlocking(false); //bind the port serverChannel.socket().bind(new InetSocketAddress(host, port)); //get the channel manager this.selector = Selector.open(); //Register the channel to manager and bind the event serverChannel.register(selector,SelectionKey.OP_READ); } /** * use asking mode to listen the event of selector * @throws IOException */ @SuppressWarnings("rawtypes") public void listen() throws IOException{ System.out.println("=========The Server is start!==========="); while(true){ selector.select(); Iterator ite = this.selector.selectedKeys().iterator(); while(ite.hasNext()){ SelectionKey key = (SelectionKey)ite.next(); ite.remove(); if (key.isReadable()) read(key); } } } /** * deal with the message come from the client * @param key * @throws IOException */ public void read(SelectionKey key) throws IOException{ DatagramChannel channel = (DatagramChannel) key.channel(); ByteBuffer buf = ByteBuffer.allocate(100); //用receive读取数据,如果用read,必须使用connect方法连接Server,并确保建立连接,write一样 InetSocketAddress socketAddress = (InetSocketAddress) channel.receive(buf); System.out.println("client ip and port:"+socketAddress.getHostString()+","+socketAddress.getPort()); byte[] data = buf.array(); String msg = new String(data).trim(); System.out.println("message come from client:"+msg); channel.send(ByteBuffer.wrap(new String("Hello client!").getBytes()),socketAddress); channel.close(); } }
Client-peer
package nio.datagramchannel; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.Iterator; /** * Client * @author donald * 2017年4月11日 * 下午9:24:09 */ public class DatagramChannelClient { //manager the channel private Selector selector; /** * stat Client * @param args * @throws IOException */ public static void main(String[] args) throws IOException{ DatagramChannelClient client = new DatagramChannelClient(); client.initClient("192.168.31.153",10001); client.listen(); } /** * get the Socket and finish some initial work * @param ip Server ip * @param port connect Server port * @throws IOException */ public void initClient(String ip,int port) throws IOException{ //get the Socket DatagramChannel channel = DatagramChannel.open(); // set no blocking mode channel.configureBlocking(false); channel.socket().bind(new InetSocketAddress(ip,port)); //get the channel manager this.selector = Selector.open(); //Register the channel to manager and bind the event channel.register(selector,SelectionKey.OP_READ); //发送数据到Server channel.send(ByteBuffer.wrap(new String("Hello Server!").getBytes()),new InetSocketAddress("192.168.31.153", 10000)); } /** * use asking mode to listen the event of selector * @throws IOException */ @SuppressWarnings("rawtypes") public void listen() throws IOException{ System.out.println("===========The Client is start!==========="); while(true){ selector.select(); Iterator ite = this.selector.selectedKeys().iterator(); while(ite.hasNext()){ SelectionKey key = (SelectionKey)ite.next(); ite.remove(); if (key.isReadable()) read(key); } } } /** * deal with the message come from the server * @param key * @throws IOException */ public void read(SelectionKey key) throws IOException{ DatagramChannel channel = (DatagramChannel) key.channel(); ByteBuffer buf = ByteBuffer.allocate(100); //用receive读取数据,如果用read,必须使用connect方法连接Server,并确保建立连接,write一样 InetSocketAddress socketAddress = (InetSocketAddress) channel.receive(buf); System.out.println("server ip and port:"+socketAddress.getHostString()+","+socketAddress.getPort()); byte[] data = buf.array(); String msg = new String(data).trim(); System.out.println("message come from server:"+msg); channel.close(); } }
先启动Server-peer,后启动Client-peer,控制台输出:
Server-peer:
=========The Server is start!===========
client ip and port:192.168.31.153,10001
message come from client:Hello Server!
Client-peer:
===========The Client is start!===========
server ip and port:192.168.31.153,10000
message come from server:Hello client!
上面的报文通道使用实例用的是send和receive方法发送和接收报文,是不需要提前建立连接的。
我们看用read和write方法发送和接收报文
Server-peer:
package nio.datagramchannel; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.Iterator; /** * Sever * @author donald * 2017年4月11日 * 下午9:24:03 */ public class UdpServer { //manager the channel private Selector selector; /** * stat Server * @param args * @throws IOException */ public static void main(String[] args) throws IOException{ UdpServer server = new UdpServer(); server.initServer("192.168.31.153", 10000); server.listen(); } /** * get the ServerSocket and finish some initial work * @param port * @throws IOException */ public void initServer(String host, int port) throws IOException{ //get the ServerSocket DatagramChannel serverChannel = DatagramChannel.open(); // set no blocking mode serverChannel.configureBlocking(false); //bind the port serverChannel.socket().bind(new InetSocketAddress(host, port)); //get the channel manager this.selector = Selector.open(); //Register the channel to manager and bind the event serverChannel.register(selector,SelectionKey.OP_READ); serverChannel.connect(new InetSocketAddress("192.168.31.153", 10001)); while(!serverChannel.isConnected()){ //空转等待连接 } } /** * use asking mode to listen the event of selector * @throws IOException */ @SuppressWarnings("rawtypes") public void listen() throws IOException{ System.out.println("=========The Server is start!==========="); while(true){ selector.select(); Iterator ite = this.selector.selectedKeys().iterator(); while(ite.hasNext()){ SelectionKey key = (SelectionKey)ite.next(); ite.remove(); if (key.isReadable()) read(key); } } } /** * deal with the message come from the client * @param key * @throws IOException */ public void read(SelectionKey key) throws IOException{ DatagramChannel channel = (DatagramChannel) key.channel(); System.out.println("is Connected:"+channel.isConnected()); ByteBuffer buf = ByteBuffer.allocate(100); InetSocketAddress socketAddress = (InetSocketAddress) channel.getRemoteAddress(); System.out.println("client ip and port:"+socketAddress.getHostString()+","+socketAddress.getPort()); channel.read(buf); byte[] data = buf.array(); String msg = new String(data).trim(); System.out.println("message come from client:"+msg); channel.write(ByteBuffer.wrap(new String("Hello client!").getBytes())); channel.close(); } }
Client-peer:
package nio.datagramchannel; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.Iterator; /** * Client * @author donald * 2017年4月11日 * 下午9:24:09 */ public class UdpClient { //manager the channel private Selector selector; /** * stat Client * @param args * @throws IOException */ public static void main(String[] args) throws IOException{ UdpClient client = new UdpClient(); client.initClient("192.168.31.153",10001); client.listen(); } /** * get the Socket and finish some initial work * @param ip Server ip * @param port connect Server port * @throws IOException */ public void initClient(String ip,int port) throws IOException{ //get the Socket DatagramChannel channel = DatagramChannel.open(); // set no blocking mode channel.configureBlocking(false); channel.socket().bind(new InetSocketAddress(ip,port)); //get the channel manager this.selector = Selector.open(); //Register the channel to manager and bind the event channel.register(selector,SelectionKey.OP_READ); channel.connect(new InetSocketAddress("192.168.31.153", 10000)); while(!channel.isConnected()){ //空转等待连接 } channel.write(ByteBuffer.wrap(new String("Hello Server!").getBytes())); System.out.println("client send message to server is done!"); } /** * use asking mode to listen the event of selector * @throws IOException */ @SuppressWarnings("rawtypes") public void listen() throws IOException{ System.out.println("===========The Client is start!==========="); while(true){ selector.select(); Iterator ite = this.selector.selectedKeys().iterator(); while(ite.hasNext()){ SelectionKey key = (SelectionKey)ite.next(); ite.remove(); if (key.isReadable()) read(key); } } } /** * deal with the message come from the server * @param key * @throws IOException */ public void read(SelectionKey key) throws IOException{ DatagramChannel channel = (DatagramChannel) key.channel(); System.out.println("is Connected:"+channel.isConnected()); ByteBuffer buf = ByteBuffer.allocate(100); InetSocketAddress socketAddress = (InetSocketAddress) channel.getRemoteAddress(); System.out.println("server ip and port:"+socketAddress.getHostString()+","+socketAddress.getPort()); channel.read(buf); byte[] data = buf.array(); String msg = new String(data).trim(); System.out.println("message come from server:"+msg); channel.close(); } }
先启动Server-peer,后启动Client-peer,控制台输出:
Server-peer:
=========The Server is start!===========
is Connected:true
client ip and port:192.168.31.153,10001
message come from client:Hello Server!
Client-peer:
client send message to server is done!
===========The Client is start!===========
is Connected:true
server ip and port:192.168.31.153,10000
message come from server:Hello client!
总结:
send和receive方法发送和接收报文,是不需要提前建立连接的,而read和write方法,
是要建立连接的与SocketChannel相同。建议用send和receive方法发送和接收报文。
发表评论
-
文件通道解析二(文件锁,关闭通道)
2017-05-16 23:17 1074文件通道解析一(读写操作,通道数据传输等):http://do ... -
文件通道解析一(读写操作,通道数据传输等)
2017-05-16 10:04 1172Reference定义(PhantomRefere ... -
文件通道创建方式综述
2017-05-15 17:39 1074Reference定义(PhantomReference,Cl ... -
文件读写方式简单综述后续(文件,流构造)
2017-05-14 23:04 1493Java Socket通信实例:http://donald-d ... -
文件读写方式简单综述
2017-05-14 11:13 1142Java Socket通信实例:http://donald-d ... -
FileChanne定义
2017-05-12 23:28 947文件读写方式简单综述:http://donald-draper ... -
SeekableByteChannel接口定义
2017-05-11 08:43 1244ByteChannel,分散聚集通道接口的定义(SocketC ... -
FileChannel示例
2017-05-11 08:37 1003前面我们看过socket通道,datagram通道,以管道Pi ... -
PipeImpl解析
2017-05-11 08:41 941ServerSocketChannel定义:http://do ... -
Pipe定义
2017-05-10 09:07 916Channel接口定义:http://donald-drape ... -
NIO-Pipe示例
2017-05-10 08:47 914PipeImpl解析:http://donald-draper ... -
DatagramChannelImpl 解析四(地址绑定,关闭通道等)
2017-05-10 08:27 790DatagramChannelImpl 解析一(初始化):ht ... -
DatagramChannelImpl 解析三(多播)
2017-05-10 08:20 1926DatagramChannelImpl 解析一(初始化):ht ... -
DatagramChannelImpl 解析二(报文发送与接收)
2017-05-09 09:03 1418DatagramChannelImpl 解析一(初始化):ht ... -
DatagramChannelImpl 解析一(初始化)
2017-05-08 21:52 1421Channel接口定义:http://donald-drape ... -
MembershipKeyImpl 简介
2017-05-08 09:11 931MembershipKey定义:http://donald-d ... -
DatagramChannel定义
2017-05-07 23:13 1238Channel接口定义:http://donald-drape ... -
MulticastChanne接口定义
2017-05-07 13:45 1146NetworkChannel接口定义:ht ... -
MembershipKey定义
2017-05-06 16:20 927package java.nio.channels; i ... -
SocketChannelImpl 解析四(关闭通道等)
2017-05-05 08:38 2549SocketChannelImpl 解析一(通道连接,发送数据 ...
相关推荐
"Java NIO实例UDP发送接收数据代码分享" Java NIO(Non-blocking I/O)是一种异步I/O模型,允许开发者在单个线程中处理多个I/O操作,从而提高程序的性能和可扩展性。在Java NIO中,DatagramChannel是专门用于发送...
在UDP NIO聊天系统中,服务器端通常会创建一个`DatagramSocket`实例,监听特定的端口,等待来自客户端的数据包。当接收到数据包时,服务器会使用选择器注册这个通道,并进行读操作。同样,客户端也会创建一个`...
也就是说,Netty 是一个基于NIO的客户,服务器端编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户,服务端应用。Netty相当简化和流线化了网络应用的编程开发过程,例如,...
1. **Mina框架简介**:Mina提供了一套丰富的API,用于处理TCP/IP、UDP等网络协议,支持Socket和NIO(非阻塞I/O)模式。它的核心组件包括Session、Filter、ProtocolCodec等,这些组件协同工作,使得开发网络应用变得...
Java Socket编程中的NIO(非阻塞I/O)在UDP通信中的应用主要涉及到高效的数据传输和并发处理。本文将深入探讨如何使用NIO与UDP结合,实现一个简单的回显服务器,即UDPEchoSelectorProtocol。 首先,我们来看一下`...
在"**NIO学习-Java源代码分享**"这个压缩包中,可能包含了关于NIO的示例代码,包括使用NIO进行文件操作、网络通信的实例,也可能包含Netty或Mina的部分源码,这些都可以作为学习和研究NIO技术的宝贵资源。...
通过`NioDatagramChannel`,我们可以监听和发送UDP数据包。 2. **配置Bootstrap**: 使用`Bootstrap`类来配置我们的客户端或服务器端。设置事件循环组、处理器管道以及连接配置。 3. **添加Handler**: 在处理器管道...
Netty是一个基于NIO的高性能、异步事件驱动的网络应用程序框架,它极大地简化了网络编程,包括TCP和UDP协议的服务器和客户端应用开发。 在Java NIO中,核心组件包括通道(Channel)、缓冲区(Buffer)和选择器...
在尚硅谷的12讲课程中,这些知识点将通过实例演示和详细解释,让学习者掌握Java NIO的精髓,并能够实际应用到项目开发中,提升系统的性能和并发处理能力。通过系统学习,开发者将更好地理解Java NIO的优势,并能在...
- **协议支持**:xSocket可能支持多种网络协议,如TCP、UDP等,方便开发者构建各种网络应用。 - **扩展性**:提供灵活的插件机制,方便添加自定义功能或扩展已有功能。 - **稳定性与安全性**:通常会包含错误处理...
7. Java NIO应用实例: - 在聊天服务器案例中,使用选择器能够实现用一个线程监听和处理多个通道中的数据传输,使得程序结构更为简洁。 - 通过注册通道到选择器并监听事件,可以实现高效的网络应用,比如聊天...
`nio-src.rar`文件中可能包含了一些NIO的示例代码,包括如何创建和操作通道、缓冲区以及选择器的实例,通过阅读和运行这些代码,可以帮助开发者深入理解NIO的工作原理和使用方法。 **8. 学习路径** 学习NIO,首先应...
在 Netty 中,我们可以使用 `NioDatagramChannel` 类来处理 UDP 通信。 创建 UDP 接收服务的关键步骤如下: 1. **初始化 Bootstrap**:首先,我们需要创建一个 `Bootstrap` 实例,这是 Netty 中启动服务器的基本...
UDT(UDP-based Data Transfer Protocol)是为了解决TCP在大数据传输时的效率问题而设计的一种用户数据报协议(UDP)上...同时,这个项目也是研究可靠UDP传输的一个很好的实例,有助于提升对网络协议和系统设计的理解。
#### 三、Java NIO 使用实例 下面是一个简单的 Java NIO 示例,展示了如何使用 `FileChannel` 和 `ByteBuffer` 进行文件复制: ```java package nio; import java.io.FileInputStream; import java.io....
"Android UDP通信库下载" 提供的库可能就是一个优化过的非阻塞I/O(Non-blocking I/O,NIO)实现,这种模式能有效提高应用性能,避免传统阻塞I/O可能导致的线程等待问题。 非阻塞I/O模型在处理多个连接时非常高效,...
Apache Mina是一个高性能的网络应用框架,主要用于简化网络服务的开发,如TCP/IP和UDP通信。在Mina中,ByteBuffer的使用是至关重要的,因为它提供了高效的数据读写机制。本篇将深入探讨Java NIO(非阻塞I/O)中的...
描述中提到的源码来源于《NIO框架入门(二):服务端基于MINA2的UDP双向通信Demo演示》这篇文章,这表明源码实例是为了解释和展示如何利用MINA2进行基于UDP的网络编程,特别是涉及到了非阻塞I/O(Non-blocking I/O, ...
在这个实例中,我们将深入探讨Java网络编程的基础及其在实际应用中的实践。本文将覆盖以下几个关键知识点: 1. **Java网络编程基础** - Java提供了丰富的类库支持网络编程,如`java.net`包下的Socket、...