java网络编程第8章举的Whois客户端例子的代码

Whois类

连接服务器

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;

import org.omg.CORBA.portable.UnknownException;

public class Whois {
	public final static int DEFAULT_PORT=43;//端口  成员变量
	public final static String DEFAULT_HOST="whois.internic.net";//地址
	private int port=DEFAULT_PORT;
	private InetAddress host;
	public Whois(InetAddress host,int port){
		this.host=host;
		this.port=port;
	}
	public Whois(InetAddress host){
		this(host,DEFAULT_PORT);//构造方法引用
	}
	public Whois(String hostname,int port)throws UnknownHostException{
		this(InetAddress.getByName(hostname),port);
	}
	public Whois(String hostname)throws UnknownHostException{
		this(InetAddress.getByName(hostname),DEFAULT_PORT);
	}
	public Whois() throws UnknownHostException{
		this(DEFAULT_HOST,DEFAULT_PORT);
	}
	public enum SearchFor{
		ANY("Any"),NETWORK("Network"),PERSON("Person"),HOST("Host"),DOMAIN("Domain"),ORGANIZATION("Organization"),
		GROUP("Group"),GATEWAY("Gateway"),ASN("Asn");
		private String label;
		private SearchFor(String label){
			this.label=label;
		}
	}
	public enum SearchIn{
		ALL(""),NAME("Name"),MAILBOX("Mailbox"),HANDLE("!");
		private String label;
		private SearchIn(String label){
			this.label=label;
		}
	}
	public String lookUpNames(String target,SearchFor category,SearchIn group,boolean exactMatch)throws IOException{
		String  suffix="";
		if(!exactMatch)suffix=".";
		String prefix=category.label+""+group.label;
		String query=prefix+target+suffix;
		Socket socket=new Socket();
		try{
			SocketAddress address=new InetSocketAddress(host,port);
			socket.connect(address);//连接服务器
			Writer out=new OutputStreamWriter(socket.getOutputStream(),"ASCII");//向服务器写数据
			BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream(),"ASCII"));//从服务器读数据
			out.write(query+"\r\n");
			out.flush();		
			StringBuilder response=new StringBuilder();
			String theLine=null;
			while((theLine=in.readLine())!=null){
				response.append(theLine);
				response.append("\r\n");				
			}
			return response.toString();
		}finally{
			socket.close();
		}
		
	}
	public InetAddress getHost(){
		return this.host;
	}
	public void setHost(String host)throws UnknownHostException{
		this.host=InetAddress.getByName(host);
	}
	

}
Whois客户端代码

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.UnknownHostException;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;

public class WhoisGUI extends JFrame{
	private JTextField searchString=new JTextField(30);  //编辑文本,单行
	private JTextArea names=new JTextArea(15,80);  //编辑文本,多行
	private JButton findButton=new JButton("Find");
	private ButtonGroup searchIn=new ButtonGroup();//多斥按钮
	private ButtonGroup searchFor=new ButtonGroup();
	private JCheckBox exactMatch=new JCheckBox("Exact Match",true);//复选框
	private JTextField chosenServer=new JTextField();
	private Whois server;
	
	public WhoisGUI(Whois whois){
		super("Whois");
		this.server=whois;
		Container pane=this.getContentPane();//初始化一个容器
		
		Font f=new Font("Monospaced",Font.PLAIN,12);
		names.setFont(f);
		names.setEditable(false);//不可编辑
		
		JPanel centerPanel=new JPanel();
		centerPanel.setLayout(new GridLayout(1,1,10,10));//布局,网格布局
		JScrollPane jsp=new JScrollPane(names);//滚动条
		centerPanel.add(jsp);
		pane.add("Center",centerPanel);
		
		JPanel northPanel=new JPanel();
		JPanel northPanelTop=new JPanel();
		northPanelTop.setLayout(new FlowLayout(FlowLayout.LEFT));//布局,流式布局
		northPanelTop.add(new JLabel("Whois:"));
		northPanelTop.add("North",searchString);
		northPanelTop.add(exactMatch);
		northPanelTop.add(findButton);
		northPanel.setLayout(new BorderLayout(2,1));
		northPanel.add("North",northPanelTop);
		JPanel northPanelBottom=new JPanel();
		northPanelBottom.setLayout(new GridLayout(1,3,5,5));
		northPanelBottom.add(initRecordType());
		northPanelBottom.add(initSearchFields());
		northPanelBottom.add(initServerChoice());
		northPanel.add("Center",northPanelBottom);
		 pane.add("North",northPanel);
		 
		 ActionListener al=new LookupNames();
		 findButton.addActionListener(al);
		 searchString.addActionListener(al);
	}
	 private JPanel initRecordType(){
		 JPanel p=new JPanel();
		 p.setLayout(new GridLayout(6,2,5,2));
		 p.add(new JLabel("Search for:"));
		 p.add(new JLabel(""));
		 JRadioButton any=new JRadioButton("Any",true);
		 any.setActionCommand("Any");
		 searchFor.add(any);
         p.add(any);	
         p.add(this.makeRadioButton("Network"));
         p.add(this.makeRadioButton("Person"));
         p.add(this.makeRadioButton("Host"));
         p.add(this.makeRadioButton("Domain"));
         p.add(this.makeRadioButton("Organization"));
         p.add(this.makeRadioButton("Group"));
         p.add(this.makeRadioButton("Gateway"));
         p.add(this.makeRadioButton("ASN"));
         return p;   
	 }
		private JRadioButton makeRadioButton(String label){
			JRadioButton button=new JRadioButton(label,false);
			button.setActionCommand(label);
			searchFor.add(button);
			return button;
		}
		private JRadioButton makeSearchInRadioButton(String label){
			JRadioButton button=new JRadioButton(label,false);
			button.setActionCommand(label);
			searchIn.add(button);
			return button;
		}
		
		private JPanel initSearchFields(){
			JPanel p=new JPanel();
			p.setLayout(new GridLayout(6,1,5,2));
			p.add(new JLabel("Search In:"));
		
			JRadioButton all=new JRadioButton("All",true);
			all.setActionCommand("All");
			searchIn.add(all);
			p.add(all);
			
			p.add(this.makeSearchInRadioButton("Name"));
			p.add(this.makeSearchInRadioButton("Mailbox"));
			p.add(this.makeSearchInRadioButton("Handle"));
			return p;		
	}
		private JPanel initServerChoice(){
			final JPanel p=new JPanel();
			p.setLayout(new GridLayout(6,1,5,2));
			p.add(new JLabel("Search At:"));
			
			chosenServer.setText(server.getHost().getHostName());
			p.add(chosenServer);
			chosenServer.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent event){
					try{
						server=new Whois(chosenServer.getText());
					}catch(UnknownHostException ex){
						JOptionPane.showMessageDialog(p,ex.getMessage(),
								"Alert",JOptionPane.ERROR_MESSAGE);
					}
				}
			});
			return p;
		}
		private class LookupNames implements ActionListener{
			public void actionPerformed(ActionEvent event){
				names.setText("");
				SwingWorker<String,Object>worker=new Lookup();
				worker.execute();
			}
		}
		private class Lookup extends SwingWorker<String,Object>{
			protected String doInBackground() throws Exception{
				Whois.SearchIn group=Whois.SearchIn.ALL;
				Whois.SearchFor category=Whois.SearchFor.ANY;
				
				String searchForLabel=searchFor.getSelection().getActionCommand();
				String searchInLabel=searchIn.getSelection().getActionCommand();
				
				if(searchInLabel.equals("Name"))group=Whois.SearchIn.NAME;
				  else if(searchInLabel.equals("Mailbox")){
					  group=Whois.SearchIn.MAILBOX;
				  }else if(searchInLabel.equals("Handle")){
					  group=Whois.SearchIn.HANDLE;
				  }
				if(searchForLabel.equals("Network")){
					category=Whois.SearchFor.NETWORK;
					}else if(searchForLabel.equals("Person")){
						category=Whois.SearchFor.PERSON;
						}else if(searchForLabel.equals("Host")){
							category=Whois.SearchFor.HOST;
							}else if(searchForLabel.equals("Domain")){
								category=Whois.SearchFor.DOMAIN;
							}else if(searchForLabel.equals("Organization")){
								category=Whois.SearchFor.ORGANIZATION;
							}else if(searchForLabel.equals("Group")){
								category=Whois.SearchFor.GROUP;
							}else if(searchForLabel.equals("Gateway")){
								category=Whois.SearchFor.GATEWAY;
							}else if(searchForLabel.equals("ASN")){
								category=Whois.SearchFor.ASN;
							}
				server.setHost(chosenServer.getText());
				return server.lookUpNames(searchString.getText(),category,group,exactMatch.isSelected());
			}
			protected void done(){
				try{
					names.setText(get());
				}catch(Exception ex){
					JOptionPane.showMessageDialog(WhoisGUI.this,ex.getMessage(),"Lookup Failed",JOptionPane.ERROR_MESSAGE);
				}
			}
			}
          public static void main(String[] args){
        	  try{
        		  Whois server=new Whois();
        		  WhoisGUI a=new WhoisGUI(server);
        		  a.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        		  a.pack();
        		  EventQueue.invokeLater(new FrameShower(a));
          }catch(UnknownHostException ex){
        	  JOptionPane.showMessageDialog(null,"Could not locate default host"+Whois.DEFAULT_HOST,
        			  "Error",JOptionPane.ERROR_MESSAGE);
          }
          }
          private static class FrameShower implements Runnable{
        	  private final Frame frame;
        	  FrameShower(Frame frame){
        		  this.frame=frame;
        	  }
        	  public void run(){
        		  frame.setVisible(true);
        	  }
          }
	

}


运行出来的效果:


第一次敲这么多代码,虽然不是自己写的,自己理解都花了好久。。。。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值