如何使用Java的网络库Mina

 我来答
影视后期制作学习
2017-05-26 · 知道合伙人教育行家
影视后期制作学习
知道合伙人教育行家
采纳数:258 获赞数:698
荣获北京智泽苑教育科技有限公司金牌教师称号。

向TA提问 私信TA
展开全部

mina 这个网络资源包。是不是通过重写了CumulativeProtocolDecoder 中的doDecoded  方法中的Iosession对象。然后对方法事事的监测,在这个方法里面加上需要监测的函数。

(1)package mina.client;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Scanner;

import mina.common.BaseConfig;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.prefixedstring.PrefixedStringCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public class MinaTimeClient {

public static void main(String[] args) {
//用于TCP/TP连接的NioSocketConnector类
IoConnector connector = new NioSocketConnector();

//增加日志过滤链
connector.getFilterChain().addLast("logger", new LoggingFilter());

//增加协议过滤链,一个Filter用于转换二进制数据或者特定的协议数据为消息对象
connector.getFilterChain().addLast(
"codec",
new ProtocolCodecFilter(new PrefixedStringCodecFactory(Charset
.forName("UTF-8"))));

//设置会处理所有被service管理的连接的handler
connector.setHandler(new TimeClientHander());

//连接到特定的remote地址,InetSocketAddress封装IP和port,Java网络编程规范,
//不提供直接的ip地址和端口的connect方法
ConnectFuture connectFuture = connector.connect(new InetSocketAddress(
"127.0.0.1", BaseConfig.PORT));

// 等待建立连接
connectFuture.awaitUninterruptibly();

System.out.println("连接成功");

//返回代表两端连接的一个对象,有读写方法以及获取本端网络设置的相关方法
IoSession session = connectFuture.getSession();

Scanner sc = new Scanner(System.in);

boolean quit = false;

//一直读取输入,并发送到对端(服务端),直到输入quit
while (!quit) {

String str = sc.next();
if (str.equalsIgnoreCase("quit")) {
quit = true;
}
//利用session写出数据
session.write(str);
}

// 关闭
if (session != null) {
if (session.isConnected()) {
session.getCloseFuture().awaitUninterruptibly();
}
//Releases any resources allocated by this service
connector.dispose(true);
}

}

}

(2)package mina.client;

import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
/**
* service所绑定的handler,当手打送消息或者发送消息等等事件发生的时候
* 就会首先触发这里的方法
* IoHandler  Handles all I/O events fired by MINA.
*/
public class TimeClientHander implements IoHandler {

@Override
public void exceptionCaught(IoSession arg0, Throwable arg1)
throws Exception {
// TODO Auto-generated method stub
arg1.printStackTrace();
}

@Override
public void messageReceived(IoSession arg0, Object message)
throws Exception {
// TODO Auto-generated method stub
System.out.println("client接受信息:" + message.toString());
}

@Override
public void messageSent(IoSession arg0, Object message) throws Exception {
// TODO Auto-generated method stub
System.out.println("client发送信息" + message.toString());
}

@Override
public void sessionClosed(IoSession session) throws Exception {
// TODO Auto-generated method stub
System.out.println("client与:" + session.getRemoteAddress().toString()
+ "断开连接");
}

@Override
public void sessionCreated(IoSession session) throws Exception {
// TODO Auto-generated method stub
System.out.println("client与:" + session.getRemoteAddress().toString()
+ "建立连接");
}

@Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
// TODO Auto-generated method stub
System.out.println("IDLE " + session.getIdleCount(status));
}

@Override
public void sessionOpened(IoSession arg0) throws Exception {
// TODO Auto-generated method stub
System.out.println("打开连接");
}

}

(3)package mina.common;

public class BaseConfig {

// 服务器端口
public static final int PORT = 9123;
}
package mina.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import mina.common.BaseConfig;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.prefixedstring.PrefixedStringCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class MinaTimeServer {
private static final int PORT = BaseConfig.PORT;

public static void main(String[] args) throws IOException {

IoAcceptor acceptor = new NioSocketAcceptor();
acceptor.getFilterChain().addLast("logger", new LoggingFilter());
acceptor.getFilterChain().addLast(
"codec",
new ProtocolCodecFilter(new PrefixedStringCodecFactory(Charset
.forName("UTF-8"))));
acceptor.setHandler(new TimeServerHandler());

/*Sets the size of the read buffer that I/O processor allocates
* per each read.  It's unusual to adjust this property because
* it's often adjusted automatically by the I/O processor
* 一次最多读取这么多字节,不足也返回
*/
acceptor.getSessionConfig().setReadBufferSize(2048);

//设置空转时间
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

acceptor.bind(new InetSocketAddress(PORT));

}
}

(4)package mina.server;

import java.util.Date;

import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

public class TimeServerHandler implements IoHandler {

@Override
public void exceptionCaught(IoSession arg0, Throwable arg1)
throws Exception {
arg1.printStackTrace();

}

@Override
public void messageReceived(IoSession session, Object message)
throws Exception {

String str = message.toString();

System.out.println("接受到的消息:" + str);

if (str.trim().equalsIgnoreCase("quit")) {
session.close(true);
return;
}
Date date = new Date();
session.write(date.toString());
System.out.println("Message written...");
}

@Override
public void messageSent(IoSession arg0, Object arg1) throws Exception {
// TODO Auto-generated method stub
System.out.println("发送信息:" + arg1.toString());
}

@Override
public void sessionClosed(IoSession session) throws Exception {
// TODO Auto-generated method stub
System.out.println("IP:" + session.getRemoteAddress().toString()
+ "断开连接");
}

@Override
public void sessionCreated(IoSession session) throws Exception {
// TODO Auto-generated method stub
System.out.println("IP:" + session.getRemoteAddress().toString());
}

@Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
// TODO Auto-generated method stub
System.out.println("IDLE " + session.getIdleCount(status));
}

@Override
public void sessionOpened(IoSession arg0) throws Exception {
// TODO Auto-generated method stub
}
}

推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式