参考:Java中的MINA框架_java mina_小陈拾光的博客-CSDN博客
MINA:一个简洁易用的基于TCP/IP通信的JAVA框架。
org.apache.mina mina-core 2.1.5
先启动server,之后启动client,则首先server和client均会创建sessionCreated 和 sessionOpened,之后client发送消息:messageSent,cf.getSession().write(msg)
则server端,可以收到消息,之后server端发送,也是session.write(msg),messageSent。可参考如下:
结果:Client端
Connected to the target VM, address: '127.0.0.1:62483', transport: 'socket'
MinaClientHandler-sessionCreated (0x00000001: nio socket, client, /127.0.0.1:62534 => localhost/127.0.0.1:9999)
MinaClientHandler-sessionOpened (0x00000001: nio socket, client, /127.0.0.1:62534 => localhost/127.0.0.1:9999)
MinaClientHandler-messageSent (0x00000001: nio socket, client, /127.0.0.1:62534 => localhost/127.0.0.1:9999) Message{from='clientfrom', to='clientto', type='clientsend', info='clientinfo'}
16:44:28.700 [NioProcessor-2] DEBUG org.apache.mina.filter.codec.ProtocolCodecFilter - Processing a MESSAGE_RECEIVED for session 1
MinaClientHandler-messageReceived (0x00000001: nio socket, client, /127.0.0.1:62534 => localhost/127.0.0.1:9999) Message{from='serverFrom', to='serverTo', type='serversent', info='serverInfo'}
服务端:server:
Connected to the target VM, address: '127.0.0.1:62391', transport: 'socket'
Mina Server Running,Listener on : 9999
MinaServerHandler sessionCreated (0x00000001: nio socket, server, /127.0.0.1:62534 => /127.0.0.1:9999)
MinaServerHandler -sessionOpened welcome client: /127.0.0.1:62534
16:44:28.684 [NioProcessor-2] DEBUG org.apache.mina.filter.codec.ProtocolCodecFilter - Processing a MESSAGE_RECEIVED for session 1
MinaServerHandler messageReceived 收到客户端发来的消息:(0x00000001: nio socket, server, /127.0.0.1:62534 => /127.0.0.1:9999) Message{from='clientfrom', to='clientto', type='clientsend', info='clientinfo'}
MinaServerHandler messageSent (0x00000001: nio socket, server, /127.0.0.1:62534 => /127.0.0.1:9999) Message{from='serverFrom', to='serverTo', type='serversent', info='serverInfo'}
如果Server不关闭,只关闭Client,则会向服务器发送:
MinaServerHandler-exceptionCaught (0x00000001: nio socket, server, /127.0.0.1:49956 => /127.0.0.1:9999) java.io.IOException: 远程主机强迫关闭了一个现有的连接。
MinaServerHandler client closed (0x00000001: nio socket, server, /127.0.0.1:49956 => 0.0.0.0/0.0.0.0:9999)
如果客户端不关闭,只关闭 服务端Server,则此时会在Client出现:
MinaClientHandler-exceptionCaught (0x00000001: nio socket, client, /127.0.0.1:50335 => localhost/127.0.0.1:9999) java.io.IOException: 远程主机强迫关闭了一个现有的连接。
MinaClientHandler-sessionClosed (0x00000001: nio socket, client, 0.0.0.0/0.0.0.0:50335 => localhost/127.0.0.1:9999)
代码如下:
package mina;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Iterator;
/**
*服务器
*/
public class Server {
public static void main(String[] args) {
//创建一个非阻塞的Server端Socket NIO
SocketAcceptor acceptor = new NioSocketAcceptor();
DefaultIoFilterChainBuilder Chain = acceptor.getFilterChain();
//设定一个过滤器,一行一行的读取数据(/r/n)
// Chain.addLast("myChain",new ProtocolCodecFilter(new TextLineCodecFactory()));
//设定过滤器,以对象为单位来读取数据
Chain.addLast("objectFilter",new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
//设置服务端的消息处理器
acceptor.setHandler(new MinaServerHandler());
//定义端口号
int port = 9999;
try {
//绑定端口,启动服务器(不会阻塞,立即返回)
acceptor.bind(new InetSocketAddress(port));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Mina Server Running,Listener on : "+port);
}
}
package mina;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
/**
*
* mina
*
* 类说明
*
* @author duanxj
* @version
*/
public class MinaServerHandler extends IoHandlerAdapter{
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
System.out.println("MinaServerHandler-exceptionCaught "+session+" "+cause);
}
//接收消息
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
super.messageReceived(session, message);
// String msg = (String) message;//接收到的消息对象
Message msg = (Message)message;
System.out.println(" MinaServerHandler messageReceived 收到客户端发来的消息:"+session+" "+msg);
//向客户端发送消息对象
msg.setFrom("serverFrom");
msg.setTo("serverTo");
msg.setType("serversent");
msg.setInfo("serverInfo");
session.write(msg);
}
@Override
public void messageSent(IoSession session, Object message) throws Exception {
System.out.println("MinaServerHandler messageSent "+session+" "+message);
}
//会话关闭
@Override
public void sessionClosed(IoSession session) throws Exception {
super.sessionClosed(session);
System.out.println("MinaServerHandler client closed "+session);
}
@Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("MinaServerHandler sessionCreated "+session);
}
@Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
System.out.println("MinaServerHandler sessionIdle "+session+" "+status);
}
//一次会话被打开
@Override
public void sessionOpened(IoSession session) throws Exception {
super.sessionOpened(session);
System.out.println(" MinaServerHandler -sessionOpened welcome client: "+session.getRemoteAddress());
}
}
package mina;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import java.net.InetSocketAddress;
import java.util.Scanner;
/**
* @date 2022/4/15--9:20
* 客户端
*/
public class Client {
public static void main(String[] args) {
//创建连接
NioSocketConnector connector = new NioSocketConnector();
DefaultIoFilterChainBuilder chain = connector.getFilterChain();
// chain.addLast("myChain",new ProtocolCodecFilter(new TextLineCodecFactory()));
//设定过滤器,以对象为单位来读取数据
chain.addLast("objectFilter",new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
connector.setHandler(new MinaClientHandler());
connector.setConnectTimeoutMillis(10000);
//连接服务器
ConnectFuture cf =connector.connect(new InetSocketAddress("localhost",9999));
cf.awaitUninterruptibly();//等待连接成功
//Scanner input = new Scanner(System.in);
// while (true){
// System.out.println("请输入:");
// String info= input.nextLine();
// //发送消息
// cf.getSession().write(info);
// }
//以对象的方式传输数据
Message msg = new Message();
//System.out.println("from:");
msg.setFrom("clientfrom");
// System.out.println("To:");
msg.setTo("clientto");
// msg.setTo(input.nextLine());
//System.out.println("info");;
msg.setInfo("clientinfo");
msg.setType("clientsend");
cf.getSession().write(msg);
//等待服务器连接关闭,结束长连接
// cf.getSession().getCloseFuture().awaitUninterruptibly()
//connector.dispose();
}
}
package mina;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
/**
* @date 2022/4/15--9:21
* 客户端消息处理器
*/
public class MinaClientHandler extends IoHandlerAdapter {
@Override
public void sessionOpened(IoSession session) throws Exception {
super.sessionOpened(session);
System.out.println("MinaClientHandler-sessionOpened "+session);
}
@Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("MinaClientHandler-sessionCreated "+session);
}
@Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
System.out.println("MinaClientHandler-sessionIdle "+session+" "+status);
}
@Override
public void sessionClosed(IoSession session) throws Exception {
super.sessionClosed(session);
System.out.println("MinaClientHandler-sessionClosed "+session);
}
@Override
public void messageSent(IoSession session, Object message) throws Exception {
System.out.println("MinaClientHandler-messageSent "+session+" "+message);
}
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
System.out.println("MinaClientHandler-exceptionCaught "+session+" "+cause);
}
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
super.messageReceived(session, message);
// String msg = (String) message;
Message msg = (Message) message;
System.out.println("MinaClientHandler-messageReceived "+session+" "+msg);
}
}
package mina;
import java.io.Serializable;
/**
* @date 2022/4/15--9:49
*/
public class Message implements Serializable {
private String from;
private String to;
private String type;
private String info;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
@Override
public String toString() {
return "Message{" +
"from='" + from + '\'' +
", to='" + to + '\'' +
", type='" + type + '\'' +
", info='" + info + '\'' +
'}';
}
}