日期:2014-05-16 浏览次数:21024 次
package com.heming.apache.mina.samplesclient; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; /** * 消息处理类 * @author 何明 * */ public class SamplMinaClientHander extends IoHandlerAdapter { @Override public void exceptionCaught(IoSession arg0, Throwable arg1) throws Exception { // TODO Auto-generated method stub } /** * 当客户端接受到消息时 */ @Override public void messageReceived(IoSession session, Object message) throws Exception { //我们已设定了服务器的消息规则是一行一行读取,这里就可以转为String: String s = (String)message; //Writer the received data back to remote peer System.out.println("服务器发来的收到消息: " + s); //测试将消息回送给客户端 session.write(s); } @Override public void messageSent(IoSession arg0, Object arg1) throws Exception { // TODO Auto-generated method stub } /** * 当一个客户端被关闭时 */ @Override public void sessionClosed(IoSession session) throws Exception { System.out.println("one client Disconnect"); } @Override public void sessionCreated(IoSession arg0) throws Exception { // TODO Auto-generated method stub } @Override public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception { // TODO Auto-generated method stub } /** * 当一个客户端连接进入时 */ @Override public void sessionOpened(IoSession session) throws Exception { System.out.println("incomming client:" + session.getRemoteAddress()); session.write("我来啦"); } } package com.heming.apache.mina.samplesclient; import java.net.InetSocketAddress; 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.textline.TextLineCodecFactory; import org.apache.mina.transport.socket.nio.NioSocketConnector; /** * 启动客户端 * @author 何明 * */ public class MainClient { public static void main(String []args)throws Exception{ //Create TCP/IP connection NioSocketConnector connector = new NioSocketConnector(); //创建接受数据的过滤器 DefaultIoFilterChainBuilder chain = connector.getFilterChain(); //设定这个过滤器将一行一行(/r/n)的读取数据 chain.addLast("myChin", new ProtocolCodecFilter(new TextLineCodecFactory())); //服务器的消息处理器:一个SamplMinaServerHander对象 connector.setHandler(new SamplMinaClientHander()); //set connect timeout connector.setConnectTimeout(30); //连接到服务器: ConnectFuture cf = connector.connect(new InetSocketAddress("localhost",8899)); //Wait for the connection attempt to be finished. cf.awaitUninterruptibly(); cf.getSession().getCloseFuture().awaitUninterruptibly(); connector.dispose(); } }