importjava.net.InetSocketAddress;importjava.nio.charset.Charset;importorg.apache.log4j.Logger;importorg.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;importorg.apache.mina.core.future.ConnectFuture;importorg.apache.mina.core.future.IoFuture;importorg.apache.mina.core.future.IoFutureListener;importorg.apache.mina.core.service.IoHandlerAdapter;importorg.apache.mina.core.session.IoSession;importorg.apache.mina.filter.codec.ProtocolCodecFilter;importorg.apache.mina.filter.codec.textline.LineDelimiter;importorg.apache.mina.filter.codec.textline.TextLineCodecFactory;importorg.apache.mina.filter.logging.LoggingFilter;importorg.apache.mina.transport.socket.DatagramConnector;importorg.apache.mina.transport.socket.nio.NioDatagramConnector;publicclassClientextendsIoHandlerAdapter {privatestaticLogger logger=Logger.getLogger(Client.class);
DatagramConnector connector;
IoSession session;publicClient() {
connector=newNioDatagramConnector();
connector.setHandler(this);
DefaultIoFilterChainBuilder chain=connector.getFilterChain();
chain.addLast("logger",newLoggingFilter());
chain.addLast("codec",newProtocolCodecFilter(newTextLineCodecFactory(Charset.forName("UTF-8"),
LineDelimiter.NUL, LineDelimiter.NUL)));
IoFuture connFuture=connector.connect(newInetSocketAddress("127.0.0.1",1234));
connFuture.addListener(newIoFutureListener() {publicvoidoperationComplete(IoFuture future) {
ConnectFuture connFuture=(ConnectFuture) future;if(connFuture.isConnected()) {
session=future.getSession();try{
sendData();
}catch(InterruptedException e) {
e.printStackTrace();
}
}else{
logger.error("Not connected...exiting");
}
}
});
}privatevoidsendData()throwsInterruptedException {
session.write("测试数据发送!");
}publicstaticvoidmain(String[] args) {newClient();
}
}