主要思路:利用Mina在指定的第三方服务器上运行server端,然后实现客户端和 第三方 服务器建立socket连接,发送ping任务的消息给第三方服务器,第三方服务器再把执行结果实时反馈给客户端。
package michael.mina.ping;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
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.SocketConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
/**
* @blog http://sjsky.iteye.com
* @author Michael
*/
public class PingClient {
private static final int PORT = 54321;
/**
* IP列表
* @param ipList
*/
public void createPingClient(List<String> ipList) {
SocketConnector connector = new NioSocketConnector();
Linux停止系统运行不关闭电源命令halt DefaultIoFilterChainBuilder chain = connector.getFilterChain();
// 设定过滤器一行一行读取数据
chain.addLast("codec", new ProtocolCodecFilter(
new TextLineCodecFactory(Charset.forName("UTF-8"))));
// 注册消息处理器
connector.setHandler(new PingClientIoHandler());
connector.setConnectTimeoutMillis(30 * 1000L);
// 连接服务器
ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1",
54321));
cf.awaitUninterruptibly();
IoSession session = cf.getSession();
for (String ip : ipList) {
session.write("ping " + ip);
}
session.getCloseFuture().awaitUninterruptibly();
connector.dispose();
System.out.println("-------------------");
}
/**
* 控制台输入
* @param ipList
*/
public void createPingClient() {
SocketConnector connector = new NioSocketConnector();
DefaultIoFilterChainBuilder chain = connector.getFilterChain();
// 设定过滤器一行一行读取数据
chain.addLast("codec", new ProtocolCodecFilter(
new TextLineCodecFactory(Charset.forName("UTF-8"))));
// 注册消息处理器
connector.setHandler(new PingClientIoHandler());
connector.setConnectTimeoutMillis(30 * 1000L);
// 连接服务器
ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1",
54321));
cf.awaitUninterruptibly();
IoSession session = cf.getSession();
Scanner input = new Scanner(System.in).useDelimiter("\\r\\n");
while (input.hasNext()) {
String s = input.next();
if (s.equals("quit")) {
break;
}
session.write(s);
}
// cf.getSession().getCloseFuture().awaitUninterruptibly();
connector.dispose();
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
PingClient tester = new PingClient();
List<String> iplist = new ArrayList<String>();
iplist.add("192.168.8.89");
iplist.add("192.168.8.93");
iplist.add("192.168.8.109");
iplist.add("192.168.8.117");
iplist.add("192.168.8.118");
tester.createPingClient(iplist);
}
}