必威体育Betway必威体育官网
当前位置:首页 > IT技术

mina案例

时间:2019-10-10 06:43:29来源:IT技术作者:seo实验室小编阅读:53次「手机版」
 

mina

mina是个很好的网络应用程序框架,支持TCP、UDP及串口通信。以下是基于TCP的案例:

1.创建一个java项目

2.下载mina包,下载地址为mina依赖包

3.导入lib和dist下的jar包

4.创建TimeServerhandler 处理类

public class TimeServerHandler extends IoHandlerAdapter {

	@Override
	public void sessionCreated(iOSession session) throws Exception {
		System.out.println("IP:" + session.getRemoteAddress().toString());
	}

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

	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		System.out.println("IDLE " + session.getIdleCount(status));
	}

	@Override
	public void messagereceived(IoSession session, Object message)
			throws Exception {
		System.out.println("发送信息:" + message.toString());
	}

	@Override
	public void messageSent(IoSession session, Object message)
			throws Exception {
		String str = message.toString();

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

		if (str.trim().equalsignorecase("quit")) {
			session.closeOnFlush();
			return;
		}
		Date date = new Date();
		String format = new simpledateformat("yyyy-MM-dd HH:MM:SSS")
				.format(date);
		session.write(format);
		System.out.println("消息已发送...");
	}
}

5.创建MinaTimeServer 服务端类

public class MinaTimeServer {

	private static final int PORT = 9123;

	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());

		acceptor.getSessionConfig().setReadBufferSize(2048);
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

		acceptor.bind(new InetSocketAddress(PORT));

	}

}

6.测试服务端

    命令行输入: telnet 127.0.0.1 9123

        

     控制台出现如下信息:

        

7.创建TimeClientHander 处理器

public class TimeClientHander extends IoHandlerAdapter {

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

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		System.out.println("打开连接");
	}

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

	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		System.out.println("IDLE " + session.getIdleCount(status));
	}

	@Override
	public void exceptionCaught(IoSession session, throwable cause)
			throws Exception {
		cause.printstacktrace();
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		System.out.println("client接受信息:" + message.toString());
	}

	@Override
	public void messageSent(IoSession session, Object message)
			throws Exception {
		System.out.println("client发送信息:" + message.toString());
	}

}

8.创建MinaTimeClient 客户端类

public class MinaTimeClient {

	public static final int PORT = 9123;

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		IoConnector connector = new NioSocketConnector();
		connector.getFilterChain().addLast("logger", new LoggingFilter());
		connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(
				new PrefixedStringCodecFactory(Charset.forName("UTF-8"))));
		connector.setHandler(new TimeClientHander());
		ConnectFuture connectFuture = connector
				.connect(new InetSocketAddress("127.0.0.1", PORT));
		//等待建立连接
		connectFuture.awaitUninterruptibly();
		System.out.println("连接成功");
		IoSession session = connectFuture.getSession();
		scanner sc = new Scanner(System.in);
		boolean quit = false;
		while (!quit) {
			String str = sc.next();
			if (str.equalsIgnoreCase("quit")) {
				quit = true;
			}
			session.write(str);
		}

		//关闭
		if (session != null) {
			if (session.isConnected()) {
				session.getCloseFuture().awaitUninterruptibly();
			}
			connector.dispose(true);
		}

	}

}

9.测试

  启动客户端类,在控制台中输入:mina客户端,如图,

        

   服务端如下图所示: 

       

当然,对于自定义协议时,只需重写DemuxingProtocolCodecFactory多路协议工厂类,并MessageDecoderAdapter 解码器和MessageEncoder<T> 编码器即可,其中T指二进制数据流编码发送前所对应的Java实体类。Netty同样也支持自定义协议,也是对NIOSocket的很好封装。

相关阅读

TerminateProcess 杀进程

今天又掉坑里了。用“TerminateProcess”杀某个控制台进程,结果进程杀死了,应用程序还停留在状态栏,任务管理器中的“进程”已找不到

java.io.IOException: UT000036: Connection terminat

java.lang.RuntimeException: java.io.IOException: UT000036: Connection terminated parsing multipart data at io.undertow.

CloseHandle(),TerminateThread(),ExitThread()的区别

线程的handle用处:线程的handle是指向“线程的内核对象”的,而不是指向线程本身.每个内核对象只是内核分配的一个内存块,并且只能由

用mac自带terminal ssh连虚拟机centos提示port 22: Op

2018.8.14 17:45更新 找到了另外一条路。终于可以用mac自带terminal ssh连虚拟机centos了。 各版本还是不变,在centos的初始状态下

WindowsAPI详解——TerminateProcess 终止|杀死其它进

WindowsAPI详解——TerminateProcess 终止|杀死其它进程 - [VC++编程]

分享到:

栏目导航

推荐阅读

热门阅读