Mina入门级客户端程序实现telnet程序

风流意气都作罢 提交于 2019-12-04 23:09:58

Mina入门级客户端程序实现telnet程序,其实mina的客户端和服务端很相似

1.编写客户端MinaClient.java和客户端处理类MyClientHandler.java
2.MinaClient.java

package com.mina;

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

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoAcceptor;
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.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public class MinaClient {
//客户端需要定义IP地址和端口
private static String host="127.0.0.1";
private static int port=7080;
public static void main(String[] args) {

IoSession session=null;
//MINA提供IOConnector
IoConnector connector=new NioSocketConnector();
//设置超时时间
connector.setConnectTimeout(3000);
//设置过滤器,主要完成编码工作
connector.getFilterChain().addLast("coderc",
//指定编码解码器
new ProtocolCodecFilter(new TextLineCodecFactory(
Charset.forName("UTF-8"),
LineDelimiter.WINDOWS.getValue(),
LineDelimiter.WINDOWS.getValue()
)));
//设置业务方法
connector.setHandler(new MyClientHandler());
//获得会话连接
ConnectFuture future=connector.connect(new InetSocketAddress(host,port));
//设置等待连接,完成连接后获得session
future.awaitUninterruptibly();
//获得session
session=future.getSession();
//往session中写入数据
session.write("你好,我是赵云!!!");
//设置服务端收到exit退出,等待关闭连接
session.getCloseFuture().awaitUninterruptibly();
//对connector实现dispose()方法
connector.dispose();
}
}

2.MyClientHandler.java

package com.mina;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
/**
* 自己的业务处理类
* 选中自己的类,source-->run as-->implement methods
* @author xjj13
*
*/
public class MyClientHandler extends IoHandlerAdapter{
//发生异常时,输出
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
System.out.println("exceptionCaught");
}

//获得信息时
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
String msg=(String)message;
System.out.println("客户端收到数据:"+msg);
}

}
3.先启动服务端,再启动客户端

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!