import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import java.net.InetSocketAddress;
import java.util.Scanner;
public class client {
public static void main(String[] args) {
NioSocketConnector conn = new NioSocketConnector();
DefaultIoFilterChainBuilder chain = conn.getFilterChain();
chain.addLast( "myChain" , new ProtocolCodecFilter( new TextLineCodecFactory()));
conn.setHandler( new MinaClientHandle());
conn.setConnectTimeoutCheckInterval(3000);
ConnectFuture cf = conn.connect( new InetSocketAddress( "localhost" , 8080));
cf.awaitUninterruptibly();
Scanner input = new Scanner(System. in );
while ( true ){
System. out .println( "输入消息" );
String msg = input.nextLine();
cf.getSession().write(msg);
}
}
}
class MinaClientHandle extends IoHandlerAdapter {
@Override
public void sessionOpened(IoSession session) throws Exception {
super.sessionOpened(session);
System. out .println( "已连接" );
}
@Override
public void sessionClosed(IoSession session) throws Exception {
super.sessionClosed(session);
System. out .println( "已关闭" );
}
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
super.messageReceived(session, message);
System. out .println( "服务器返回消息:" +message);
}
}
|