- 浏览: 15333 次
文章分类
最新评论
根据Mina的官方例子修改而来。
server端:
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package com.taobao.mina.myudp;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.ConcurrentHashMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.DatagramSessionConfig;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;
/**
* The class that will accept and process clients in order to properly
* track the memory usage.
*
* @author <a href="http://mina.apache.org" mce_href="http://mina.apache.org">Apache MINA Project</a>
*/
public class MemoryMonitor {
private static final long serialVersionUID = 1L;
public static final int PORT = 18567;
public MemoryMonitor() throws IOException {
// 创建UDP数据包NIO
NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
// NIO设置底层IOHandler 把服务器的本身传入
acceptor.setHandler(new MemoryMonitorHandler(this));
// 设置filter
DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
chain.addLast("logger", new LoggingFilter());
// 设置是否重用地址? 也就是每个发过来的udp信息都是一个地址?
DatagramSessionConfig dcfg = acceptor.getSessionConfig();
dcfg.setReuseAddress(true);
// 绑定端口地址
acceptor.bind(new InetSocketAddress(PORT));
System.out.println("UDPServer listening on port " + PORT);
}
public static void main(String[] args) {
try {
new MemoryMonitor();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package com.taobao.mina.myudp;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Date;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
/**
* Class the extends IoHandlerAdapter in order to properly handle
* connections and the data the connections send
*
* @author <a href="http://mina.apache.org" mce_href="http://mina.apache.org">Apache MINA Project</a>
*/
public class MemoryMonitorHandler extends IoHandlerAdapter {
private MemoryMonitor server;
public MemoryMonitorHandler(MemoryMonitor server) {
this.server = server;
}
/**
* 异常来关闭session
*/
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
cause.printStackTrace();
session.close(true);
}
/**
* 服务器端收到一个消息
*/
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
if (message instanceof IoBuffer) {
IoBuffer buffer = (IoBuffer) message;
buffer.setAutoExpand(true);
System.out.println("服务器端获得udp信息:" + buffer.getLong());
Charset c = Charset.forName("UTF-8");
CharsetEncoder ce = c.newEncoder();
// 给client返回信息 IoBuffer.wrap
IoBuffer clientBuffer = IoBuffer.wrap((new Date().toLocaleString() + "服务器已收到。").getBytes(c));
clientBuffer.setAutoExpand(true);
session.setAttribute("clientbuffer", clientBuffer);
session.write(clientBuffer);
}
}
@Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("服务器端关闭session...");
}
@Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("服务器端成功创建一个session...");
}
@Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
// System.out.println("Session idle...");
}
@Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("服务器端成功开启一个session...");
}
}
client端:
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package com.taobao.mina.myudp.client;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.example.udp.MemoryMonitor;
import org.apache.mina.transport.socket.nio.NioDatagramConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Sends its memory usage to the MemoryMonitor server.
* 这样的写法 将本来可以单独的client写到IoHandlerAdapter 更紧凑
*
* @author <a href="http://mina.apache.org" mce_href="http://mina.apache.org">Apache MINA Project</a>
*/
public class MemMonClient extends IoHandlerAdapter {
private final static Logger LOGGER = LoggerFactory.getLogger(MemMonClient.class);
private IoSession session;
private IoConnector connector;
/**
* Default constructor.
*/
public MemMonClient() {
connector = new NioDatagramConnector();
connector.setHandler(this);
ConnectFuture connFuture = connector.connect(new InetSocketAddress(
"localhost", MemoryMonitor.PORT)); // 这样不太好吧
connFuture.awaitUninterruptibly();
// 给conn添加一个监听器
connFuture.addListener(new IoFutureListener<ConnectFuture>() {
public void operationComplete(ConnectFuture future) {
if (future.isConnected()) {
session = future.getSession();
try {
sendData();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
throw new Exception(" 连接错误。 ");
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
private void sendData() throws InterruptedException {
for (int i = 0; i < 10; i++) {
long free = Runtime.getRuntime().freeMemory(); // 得到当前空闲内存大小
IoBuffer buffer = IoBuffer.allocate(8);
buffer.putLong(free); // 只把剩余内存大小放入buffer, 扔给server
buffer.flip();
session.write(buffer); // 写入
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
throw new InterruptedException(e.getMessage());
}
}
}
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
cause.printStackTrace();
}
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
Charset c = Charset.forName("UTF-8");
CharsetDecoder cd = c.newDecoder();
IoBuffer buffer = (IoBuffer)message;
System.out.println("客户端收到来自服务器的消息String:" + (buffer.getString(cd)));
}
@Override
public void messageSent(IoSession session, Object message) throws Exception {
System.out.println("客户端向服务器发送信息:" + ((IoBuffer)message).getLong());
}
@Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("客户端关闭了当前会话");
}
@Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("客户端成功创建session");
}
@Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
}
@Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("客户端成功开启一个session id:"+session.getId());
}
public static void main(String[] args) {
new MemMonClient();
}
}
server端:
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package com.taobao.mina.myudp;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.ConcurrentHashMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.DatagramSessionConfig;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;
/**
* The class that will accept and process clients in order to properly
* track the memory usage.
*
* @author <a href="http://mina.apache.org" mce_href="http://mina.apache.org">Apache MINA Project</a>
*/
public class MemoryMonitor {
private static final long serialVersionUID = 1L;
public static final int PORT = 18567;
public MemoryMonitor() throws IOException {
// 创建UDP数据包NIO
NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
// NIO设置底层IOHandler 把服务器的本身传入
acceptor.setHandler(new MemoryMonitorHandler(this));
// 设置filter
DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
chain.addLast("logger", new LoggingFilter());
// 设置是否重用地址? 也就是每个发过来的udp信息都是一个地址?
DatagramSessionConfig dcfg = acceptor.getSessionConfig();
dcfg.setReuseAddress(true);
// 绑定端口地址
acceptor.bind(new InetSocketAddress(PORT));
System.out.println("UDPServer listening on port " + PORT);
}
public static void main(String[] args) {
try {
new MemoryMonitor();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package com.taobao.mina.myudp;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Date;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
/**
* Class the extends IoHandlerAdapter in order to properly handle
* connections and the data the connections send
*
* @author <a href="http://mina.apache.org" mce_href="http://mina.apache.org">Apache MINA Project</a>
*/
public class MemoryMonitorHandler extends IoHandlerAdapter {
private MemoryMonitor server;
public MemoryMonitorHandler(MemoryMonitor server) {
this.server = server;
}
/**
* 异常来关闭session
*/
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
cause.printStackTrace();
session.close(true);
}
/**
* 服务器端收到一个消息
*/
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
if (message instanceof IoBuffer) {
IoBuffer buffer = (IoBuffer) message;
buffer.setAutoExpand(true);
System.out.println("服务器端获得udp信息:" + buffer.getLong());
Charset c = Charset.forName("UTF-8");
CharsetEncoder ce = c.newEncoder();
// 给client返回信息 IoBuffer.wrap
IoBuffer clientBuffer = IoBuffer.wrap((new Date().toLocaleString() + "服务器已收到。").getBytes(c));
clientBuffer.setAutoExpand(true);
session.setAttribute("clientbuffer", clientBuffer);
session.write(clientBuffer);
}
}
@Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("服务器端关闭session...");
}
@Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("服务器端成功创建一个session...");
}
@Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
// System.out.println("Session idle...");
}
@Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("服务器端成功开启一个session...");
}
}
client端:
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package com.taobao.mina.myudp.client;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.example.udp.MemoryMonitor;
import org.apache.mina.transport.socket.nio.NioDatagramConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Sends its memory usage to the MemoryMonitor server.
* 这样的写法 将本来可以单独的client写到IoHandlerAdapter 更紧凑
*
* @author <a href="http://mina.apache.org" mce_href="http://mina.apache.org">Apache MINA Project</a>
*/
public class MemMonClient extends IoHandlerAdapter {
private final static Logger LOGGER = LoggerFactory.getLogger(MemMonClient.class);
private IoSession session;
private IoConnector connector;
/**
* Default constructor.
*/
public MemMonClient() {
connector = new NioDatagramConnector();
connector.setHandler(this);
ConnectFuture connFuture = connector.connect(new InetSocketAddress(
"localhost", MemoryMonitor.PORT)); // 这样不太好吧
connFuture.awaitUninterruptibly();
// 给conn添加一个监听器
connFuture.addListener(new IoFutureListener<ConnectFuture>() {
public void operationComplete(ConnectFuture future) {
if (future.isConnected()) {
session = future.getSession();
try {
sendData();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
throw new Exception(" 连接错误。 ");
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
private void sendData() throws InterruptedException {
for (int i = 0; i < 10; i++) {
long free = Runtime.getRuntime().freeMemory(); // 得到当前空闲内存大小
IoBuffer buffer = IoBuffer.allocate(8);
buffer.putLong(free); // 只把剩余内存大小放入buffer, 扔给server
buffer.flip();
session.write(buffer); // 写入
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
throw new InterruptedException(e.getMessage());
}
}
}
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
cause.printStackTrace();
}
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
Charset c = Charset.forName("UTF-8");
CharsetDecoder cd = c.newDecoder();
IoBuffer buffer = (IoBuffer)message;
System.out.println("客户端收到来自服务器的消息String:" + (buffer.getString(cd)));
}
@Override
public void messageSent(IoSession session, Object message) throws Exception {
System.out.println("客户端向服务器发送信息:" + ((IoBuffer)message).getLong());
}
@Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("客户端关闭了当前会话");
}
@Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("客户端成功创建session");
}
@Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
}
@Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("客户端成功开启一个session id:"+session.getId());
}
public static void main(String[] args) {
new MemMonClient();
}
}
相关推荐
**Mina UDP Demo详解** Mina (Java Invented Network Application Platform) 是一款强大的网络通信框架,主要用于构建高性能、高可用性的网络应用。它提供了一种简单的方式来处理TCP/IP和UDP/IP协议,使得开发者...
本文将深入探讨如何使用Mina库在Android客户端与Java服务器之间实现UDP(用户数据报协议)的数据交互。 UDP是一种无连接的、不可靠的传输层协议,相比TCP,它具有更低的延迟和更高的数据传输效率。然而,由于其不...
标题中的“udp.rar_MINA udp_android mina UDP_mina_mina u”暗示了这是一个关于使用MINA框架在Android平台上实现UDP通信的资源包。MINA(Multipurpose Infrastructure for Network Applications)是一个高性能、...
3. **丰富的协议支持**:Mina内置了许多常见的协议处理器,如TCP、UDP、HTTP、FTP等,使得开发者能够快速实现特定的网络协议。 4. **可扩展性强**:Mina的设计允许开发者自定义过滤器链,方便添加新的功能和处理逻辑...
总的来说,基于MINA的UDP数据库连接池实现了高效、可靠的UDP数据接收和数据库操作,利用了MINA的异步特性、线程池的并发处理能力以及数据库连接池的资源复用,有效解决了UDP通信与数据库交互中的性能和稳定性问题。...
本源码是《NIO框架入门(三):iOS与MINA2、Netty4的跨平台UDP双向通信实战》一文的服务端实现(MINA2版),详见:http://www.52im.net/thread-378-1-1.html
工作中的一个小项目,分享给大家参考,望大家不吝批评指教,本人常年从事JAVA软件开发,有丰富的MINA通信软件开发经验,现在已经有成熟的底层框架(结合了反射、DynaBean、Spring等多种技术),可以实现程序自动对...
“服务端基于MINA2的UDP双向通信Demo演示(MINA2服务端)” 这个标题表明这是一个使用MINA2框架在服务端实现的UDP(User Datagram Protocol)双向通信的示例代码。MINA2是一个开源的Java网络应用程序框架,它简化了...
在本文中,我们将深入探讨mina如何实现TCP和UDP的通信,并通过实例来进一步理解其工作原理。 首先,TCP(传输控制协议)是一种面向连接的、可靠的传输协议,它确保数据包按照正确的顺序到达目的地,且无遗漏。mina...
标题中的“服务端基于MINA2的UDP双向通信Demo演示(Java客户端)”是指使用Apache MINA框架在Java中实现的UDP(用户数据报协议)的双向通信示例。MINA是一个高性能、异步的网络应用程序框架,常用于构建网络服务,如...
在这个“mina 实现简单通讯”的项目中,我们看到了一个基于MINA的基本通信实现,涵盖了服务端和客户端的交互。 首先,MINA的核心组件包括`IoSession`,它是网络连接的抽象,包含了与特定连接相关的所有信息,如输入...
最近做rfid读写,C#和java都用udp不用厂家的动态库,udp自己写也简单,但是试了一下Apache mina ,接收的不是string,二十byte[] 数组,简单实现了UDP,网上也有例子,但是不是我要的。可用。
MINA(Java Mini Asynchronous Network Application Framework)是一个高性能、异步事件驱动的网络应用程序框架,主要用于简化开发服务器和客户端的网络应用,特别是TCP和UDP协议的应用。MINA为开发者提供了高度抽象...
它提供了一种简单而强大的API,用于处理TCP/IP和UDP/IP协议,以及SSL/TLS加密的网络通信。Mina的核心理念是异步非阻塞I/O,这使得它在处理大量并发连接时表现优秀。 **CMPP2.0协议** CMPP(China Mobile Short ...
Apache Mina是一个流行的Java框架,专门用于简化和优化网络应用开发,它支持多种协议如TCP/IP、UDP/IP等,并提供了长连接和短连接的支持。在这个实例中,我们将探讨如何使用Mina实现长连接和短连接。 首先,理解长...
MINA是一个高度可扩展的网络应用框架,广泛用于构建高性能、高并发的网络应用程序,如服务器端的TCP和UDP服务。本文将主要关注在Java中使用MINA来实现安全套接层(SSL)和传输层安全(TLS)协议,这两个协议是网络...
Mina提供了一套完整的API,包括事件驱动、异步通信以及各种协议的支持,如TCP/IP、UDP/IP和SSL/TLS等。在实现双机通讯时,我们通常会使用TCP协议,因为其具有面向连接、可靠传输的特点,适合于需要稳定数据交换的...
在这个场景中,我们将讨论如何使用MINA来实现一个简单的登录功能。 首先,理解MINA的基本工作原理至关重要。MINA的核心是IoSession对象,它代表了服务器和客户端之间的持久连接。当客户端连接到服务器时,MINA会...
Mina(全称“MINA: Minimalistic Application Networking API”)是Apache软件基金会的一个开源项目,它为开发者提供了一种简单而高效的方式来构建高性能、跨平台的网络应用。Mina的核心优势在于它的事件驱动和异步I...
总之,Apache Mina提供了一种灵活且高效的方式来实现RPC,它的事件驱动模型和强大的过滤器框架使得构建网络服务变得更加简单。在实际开发中,可以根据具体需求调整和扩展这些基础架构,以满足不同场景下的性能和功能...