有时需要在部署程序前检查网络环境,要检测端口是否通畅,可能有防火墙阻止的问题。
于是我写了个小程序,监听任意指定端口,然后可以在外面telnet 该端口,并输入文字,监听段会把文字打印到控制台中,已检测网络状况。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.regex.Pattern;
public class PortListener {
public static void main(String[] argd)throws Exception{
System.out.println("A started");
int port = getListenPort();
System.out.println("Listening at port "+port+" ...");
ServerSocket server = new ServerSocket(port);
Socket client = server.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
while(true){
String w = reader.readLine();
if(w.equals("end")){
break;
}
System.out.println(w);
}
System.out.println("A ended");
}
public static int getListenPort()throws Exception{
String port=null;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while(port==null||!Pattern.matches("^\\d{2,}$", port)){
System.out.print("Enter listen port:");
port = reader.readLine();
}
reader.close();
return Integer.parseInt(port);
}
}