- 浏览: 2539861 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
MINA(5)CHAT Example
Try to learn from the sample D:\book\mina\apache-mina-2.0.4\src\mina-example
serverContext.xml
ChatProtocolHandler.java
SpringMain.java
SwingChatClient.java
I move them into my project easynio. And make the MINA chat demo and Caculate demo working fine together.
Changes in Spring Configuration:
mina-context.xml
...snip...
<bean id="chatHandler" class="com.sillycat.easynio.plugins.mina.businesshandlers.ChatHandler" />
<bean id="chatAcceptor" class="org.apache.mina.transport.socket.nio.NioSocketAcceptor"
destroy-method="unbind" init-method="bind" >
<property name="defaultLocalAddress" value=":12346" />
<property name="handler" ref="chatHandler" />
<property name="reuseAddress" value="true" />
<property name="filterChainBuilder" ref="filterChainBuilder" />
</bean>
I configured the port to 12346 to accept the chat command from the client side.
Some java classes are copied from the sample, I did not change them.
package com.sillycat.easynio.plugins.mina.businesshandlers;
public class ChatCommand {
public static final int LOGIN = 0;
public static final int QUIT = 1;
public static final int BROADCAST = 2;
private final int num;
private ChatCommand(int num) {
this.num = num;
}
public int toInt() {
return num;
}
public static ChatCommand valueOf(String s) {
s = s.toUpperCase();
if ("LOGIN".equals(s)) {
return new ChatCommand(LOGIN);
}
if ("QUIT".equals(s)) {
return new ChatCommand(QUIT);
}
if ("BROADCAST".equals(s)) {
return new ChatCommand(BROADCAST);
}
throw new IllegalArgumentException("Unrecognized command: " + s);
}
}
package com.sillycat.easynio.plugins.mina.businesshandlers;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.logging.MdcInjectionFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ChatHandler extends IoHandlerAdapter {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final Set<IoSession> sessions = Collections.synchronizedSet(new HashSet<IoSession>());
private final Set<String> users = Collections.synchronizedSet(new HashSet<String>());
public void exceptionCaught(IoSession session, Throwable cause) {
logger.warn("Unexpected exception.", cause);
session.close(true);
}
public void messageReceived(IoSession session, Object message) {
logger.info("received: " + message);
String theMessage = (String) message;
String[] result = theMessage.split(" ", 2);
String theCommand = result[0];
try {
ChatCommand command = ChatCommand.valueOf(theCommand);
String user = (String) session.getAttribute("user");
switch (command.toInt()) {
case ChatCommand.QUIT:
session.write("QUIT OK");
session.close(true);
break;
case ChatCommand.LOGIN:
if (user != null) {
session.write("LOGIN ERROR user " + user + " already logged in.");
return;
}
if (result.length == 2) {
user = result[1];
} else {
session.write("LOGIN ERROR invalid login command.");
return;
}
// check if the user name is already used
if (users.contains(user)) {
session.write("LOGIN ERROR the name " + user + " is already used.");
return;
}
sessions.add(session);
session.setAttribute("user", user);
MdcInjectionFilter.setProperty(session, "user", user);
// Allow all users
users.add(user);
session.write("LOGIN OK");
broadcast("The user " + user + " has joined the chat session.");
break;
case ChatCommand.BROADCAST:
if (result.length == 2) {
broadcast(user + ": " + result[1]);
}
break;
default:
logger.info("Unhandled command: " + command);
break;
}
} catch (IllegalArgumentException e) {
logger.debug("Illegal argument", e);
}
}
public void broadcast(String message) {
synchronized (sessions) {
for (IoSession session : sessions) {
if (session.isConnected()) {
session.write("BROADCAST OK " + message);
}
}
}
}
public void sessionClosed(IoSession session) throws Exception {
String user = (String) session.getAttribute("user");
users.remove(user);
sessions.remove(session);
broadcast("The user " + user + " has left the chat session.");
}
public boolean isChatUser(String name) {
return users.contains(name);
}
public int getNumberOfUsers() {
return users.size();
}
public void kick(String name) {
synchronized (sessions) {
for (IoSession session : sessions) {
if (name.equals(session.getAttribute("user"))) {
session.close(true);
break;
}
}
}
}
}
After I start the server side, I can use command line to connect to the server side via telnet.
>telnet localhost 12346
>login hello
LOGIN OK
BROADCAST OK The user hello has joined the chat session.
>broadcast I will check the server
BROADCAST OK hello: I will check the server
>quit
QUIT OK
From the mx4j, I can manage my bean via this URL:
http://localhost:8000/mbean?objectname=com.sillycat%3AchatHandler%3DChatHandlerJMX
references:
http://mina.apache.org/user-guide.html
http://blog.csdn.net/xiejn/article/details/789454
http://liangwj72.iteye.com/blog/123842
http://mx4j.sourceforge.net/
http://www.blogjava.net/freeman1984/archive/2011/02/15/344370.html
http://www.mularien.com/blog/2007/11/09/5-minute-guide-to-spring-and-jmx/
http://blog.csdn.net/shirdrn/article/details/6358688
http://topmanopensource.iteye.com/blog/832848
http://topmanopensource.iteye.com/blog/832851
http://topmanopensource.iteye.com/blog/832855
Try to learn from the sample D:\book\mina\apache-mina-2.0.4\src\mina-example
serverContext.xml
ChatProtocolHandler.java
SpringMain.java
SwingChatClient.java
I move them into my project easynio. And make the MINA chat demo and Caculate demo working fine together.
Changes in Spring Configuration:
mina-context.xml
...snip...
<bean id="chatHandler" class="com.sillycat.easynio.plugins.mina.businesshandlers.ChatHandler" />
<bean id="chatAcceptor" class="org.apache.mina.transport.socket.nio.NioSocketAcceptor"
destroy-method="unbind" init-method="bind" >
<property name="defaultLocalAddress" value=":12346" />
<property name="handler" ref="chatHandler" />
<property name="reuseAddress" value="true" />
<property name="filterChainBuilder" ref="filterChainBuilder" />
</bean>
I configured the port to 12346 to accept the chat command from the client side.
Some java classes are copied from the sample, I did not change them.
package com.sillycat.easynio.plugins.mina.businesshandlers;
public class ChatCommand {
public static final int LOGIN = 0;
public static final int QUIT = 1;
public static final int BROADCAST = 2;
private final int num;
private ChatCommand(int num) {
this.num = num;
}
public int toInt() {
return num;
}
public static ChatCommand valueOf(String s) {
s = s.toUpperCase();
if ("LOGIN".equals(s)) {
return new ChatCommand(LOGIN);
}
if ("QUIT".equals(s)) {
return new ChatCommand(QUIT);
}
if ("BROADCAST".equals(s)) {
return new ChatCommand(BROADCAST);
}
throw new IllegalArgumentException("Unrecognized command: " + s);
}
}
package com.sillycat.easynio.plugins.mina.businesshandlers;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.logging.MdcInjectionFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ChatHandler extends IoHandlerAdapter {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final Set<IoSession> sessions = Collections.synchronizedSet(new HashSet<IoSession>());
private final Set<String> users = Collections.synchronizedSet(new HashSet<String>());
public void exceptionCaught(IoSession session, Throwable cause) {
logger.warn("Unexpected exception.", cause);
session.close(true);
}
public void messageReceived(IoSession session, Object message) {
logger.info("received: " + message);
String theMessage = (String) message;
String[] result = theMessage.split(" ", 2);
String theCommand = result[0];
try {
ChatCommand command = ChatCommand.valueOf(theCommand);
String user = (String) session.getAttribute("user");
switch (command.toInt()) {
case ChatCommand.QUIT:
session.write("QUIT OK");
session.close(true);
break;
case ChatCommand.LOGIN:
if (user != null) {
session.write("LOGIN ERROR user " + user + " already logged in.");
return;
}
if (result.length == 2) {
user = result[1];
} else {
session.write("LOGIN ERROR invalid login command.");
return;
}
// check if the user name is already used
if (users.contains(user)) {
session.write("LOGIN ERROR the name " + user + " is already used.");
return;
}
sessions.add(session);
session.setAttribute("user", user);
MdcInjectionFilter.setProperty(session, "user", user);
// Allow all users
users.add(user);
session.write("LOGIN OK");
broadcast("The user " + user + " has joined the chat session.");
break;
case ChatCommand.BROADCAST:
if (result.length == 2) {
broadcast(user + ": " + result[1]);
}
break;
default:
logger.info("Unhandled command: " + command);
break;
}
} catch (IllegalArgumentException e) {
logger.debug("Illegal argument", e);
}
}
public void broadcast(String message) {
synchronized (sessions) {
for (IoSession session : sessions) {
if (session.isConnected()) {
session.write("BROADCAST OK " + message);
}
}
}
}
public void sessionClosed(IoSession session) throws Exception {
String user = (String) session.getAttribute("user");
users.remove(user);
sessions.remove(session);
broadcast("The user " + user + " has left the chat session.");
}
public boolean isChatUser(String name) {
return users.contains(name);
}
public int getNumberOfUsers() {
return users.size();
}
public void kick(String name) {
synchronized (sessions) {
for (IoSession session : sessions) {
if (name.equals(session.getAttribute("user"))) {
session.close(true);
break;
}
}
}
}
}
After I start the server side, I can use command line to connect to the server side via telnet.
>telnet localhost 12346
>login hello
LOGIN OK
BROADCAST OK The user hello has joined the chat session.
>broadcast I will check the server
BROADCAST OK hello: I will check the server
>quit
QUIT OK
From the mx4j, I can manage my bean via this URL:
http://localhost:8000/mbean?objectname=com.sillycat%3AchatHandler%3DChatHandlerJMX
references:
http://mina.apache.org/user-guide.html
http://blog.csdn.net/xiejn/article/details/789454
http://liangwj72.iteye.com/blog/123842
http://mx4j.sourceforge.net/
http://www.blogjava.net/freeman1984/archive/2011/02/15/344370.html
http://www.mularien.com/blog/2007/11/09/5-minute-guide-to-spring-and-jmx/
http://blog.csdn.net/shirdrn/article/details/6358688
http://topmanopensource.iteye.com/blog/832848
http://topmanopensource.iteye.com/blog/832851
http://topmanopensource.iteye.com/blog/832855
发表评论
-
Stop Update Here
2020-04-28 09:00 310I will stop update here, and mo ... -
NodeJS12 and Zlib
2020-04-01 07:44 467NodeJS12 and Zlib It works as ... -
Docker Swarm 2020(2)Docker Swarm and Portainer
2020-03-31 23:18 361Docker Swarm 2020(2)Docker Swar ... -
Docker Swarm 2020(1)Simply Install and Use Swarm
2020-03-31 07:58 363Docker Swarm 2020(1)Simply Inst ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 328Traefik 2020(1)Introduction and ... -
Portainer 2020(4)Deploy Nginx and Others
2020-03-20 12:06 419Portainer 2020(4)Deploy Nginx a ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 428Private Registry 2020(1)No auth ... -
Docker Compose 2020(1)Installation and Basic
2020-03-15 08:10 364Docker Compose 2020(1)Installat ... -
VPN Server 2020(2)Docker on CentOS in Ubuntu
2020-03-02 08:04 444VPN Server 2020(2)Docker on Cen ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 376Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 464NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 413Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 330Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 242GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 443GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 320GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 306Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 310Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 285Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 302Serverless with NodeJS and Tenc ...
相关推荐
5. **Session Configuration**:Mina允许我们自定义Session的配置,如读写超时、缓冲区大小等,以适应不同的应用场景。 在实际开发中,我们可以通过创建HttpServer实例,设置Acceptor、Filter Chain和EventHandler...
这个压缩包"apache.mina.example"包含了一系列的示例项目,可以帮助开发者快速上手并深入理解Mina。 1. **Mina框架概述** Mina(Minimum Asynchronous Network)是一个基于Java的网络通信库,它提供了简单、高性能...
mina-core-2.0.0-M1.jar/mina-example-1.0.5.jar/slf4j-jdk14-1.6.1.jar/slf4j-log4j12-1.6.1.jar mina 所用jar
MINA开发核心jar包,mina-example-2.0.4.jar 发出来供大家使用!
5. **启动服务器**:通过ServerBootstrap的bind方法启动监听指定端口的服务器。 6. **处理WebSocket帧**:在messageReceived方法中,根据接收到的WebSocket帧类型进行相应的处理,如发送回文本或二进制数据,或者...
mina-example-2.0.0-M6.jar mina-filter-codec-netty-2.0.0-M6.jar mina-filter-compression-2.0.0-M6.jar mina-integration-beans-2.0.0-M6.jar mina-integration-jmx-2.0.0-M6.jar mina-integration-ognl-2.0.0-M6...
5. **Mina发送XML和JSON** XML和JSON作为常见的数据交换格式,经常在分布式系统中使用。Mina可以通过集成如JAXB(Java Architecture for XML Binding)或Jackson这样的库,将XML和JSON文档转换为字节流进行传输。...
5. **Executor**:Mina使用Executor服务来管理和调度任务,确保异步操作的执行。 6. **Transport Layer**:Mina支持多种传输层实现,如TCP、UDP等,这些都抽象为IoAcceptor和IoConnector接口,方便开发者使用。 ...
最新的 mina相关jar包 合集,里边有apache-mina-2.0.7-bin.zip,apache-mina-2.0.7-src.zip,log4j-1.2.17.zip,slf4j-api-1.6.6.jar,slf4j-api-1.6.6-sources.jar,slf4j-log4j12-1.6.6.jar,mina-example-2.0.7....
apache-mina-2.0.7-bin.zip,apache-mina-2.0.7-src.zip,log4j-1.2.17.zip,slf4j-api-1.6.6.jar,slf4j-api-1.6.6-sources.jar,slf4j-log4j12-1.6.6.jar,mina-example-2.0.7.jar,mina-example-2.0.7-sources....
MINA (Java IO Network Application Framework) 是一个由Apache软件基金会开发的开源网络通信框架,主要应用于构建高性能、高可用性的网络服务器。这个压缩包包含了MINA API文档、自学手册以及开发指南,对于学习和...
5. **恢复状态**:如果可能,恢复断线前的会话状态,例如,重传未完成的请求或恢复会话上下文。 在Android平台上,Mina可以被用于开发移动应用,实现与服务器的稳定通信。需要注意的是,由于Android系统特性,如...
- 文件`example`可能包含了一个使用mina编写的服务器或客户端程序,其中包含了自定义编解码器的应用实例。 - `MinaCodec`可能是一个包含编码器和解码器的类,我们来详细分析其工作流程: - 在编码器中,通常有一...
Mina和Socket是两种常见的网络通信框架和技术,它们在Java编程环境中被广泛使用。本篇文章将深入探讨如何使用Mina与Socket实现通信,并提供客户端和服务端的实现代码概述。 Mina(全称“MINA: Minimalistic ...
mina-example-2.0.7.jar包含了MINA提供的示例代码,这些例子覆盖了各种常见的网络应用场景,包括HTTP服务器、聊天应用等,可以帮助开发者快速理解和学习如何使用MINA进行网络编程。 mina-statemachine-2.0.7.jar...
5. **高性能**:MINA的高性能主要源于其内存管理机制和零拷贝技术,减少了CPU的负载和内存中的数据复制。 6. **丰富的API**:MINA提供了一套完整的API,包括Filter(过滤器)机制,可以方便地对网络数据流进行拦截...
mina新手案例,mina新手教程源码 mina+springboot最简单的案例。用的IDEA * mina服务端 * 1、添加@Controller注解和 @PostConstruct注解,代表启动springboot项目时也调用该类下的该方法, * 启动springboot项目...
Apache Mina是一个开源项目,它提供了一个高度可扩展的网络通信框架,用于简化开发高性能、高可用性的网络服务器和客户端应用程序。"Mina demo mina jar包"指的是使用Apache Mina框架创建的一个演示示例,这个示例...
Apache Mina是一个高度可扩展的Java网络通信框架,它提供了简单而强大的开发接口,用于创建高性能、高效率的网络应用程序。Mina的核心理念是将网络协议处理与业务逻辑分离,使得开发者可以专注于实现应用程序的业务...
5. **NIO_TEST**:这可能是一些与Java NIO(非阻塞I/O)相关的测试代码或实验,MINA是基于Java NIO构建的,因此理解NIO对于使用MINA至关重要。 6. **MINA使用手记[1] _files**:这可能是一个文件夹,包含与第一篇...