/*
图形界面模拟浏览器
*/
package net.socket.tcp;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class GUIBrowser
{
private Frame f;
private Button b;
private TextField tf;
private TextArea ta;
private Dialog d;
private Button but;
private Label lab;;
GUIBrowser()
{
init();
}
public void init()
{
f = new Frame("窗体测试");
f.setBounds(300,100,600,500);
f.setLayout(new FlowLayout());
tf = new TextField(50);
b = new Button("转到");
ta = new TextArea(25,40);
f.add(tf);
f.add(b);
f.add(ta);
d = new Dialog(f,"错误提示信息",true);
d.setBounds(500,300,300,100);
d.setLayout(new FlowLayout());
lab = new Label();
but = new Button("确定");
d.add(lab);
d.add(but);
myEvent();
f.setVisible(true);
}
private void myEvent()
{
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
//通过按钮“转到”实现目录输出功能及对话框弹出功能
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
showDir();
}
catch (Exception ex)
{
}
}
});
//实现对话框的窗口关闭功能
d.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
d.setVisible(false);
}
});
//实现对话框上的按钮“确定”的功能
but.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d.setVisible(false);
}
});
//通过回车键实现按钮“转到”的功能
tf.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode()==KeyEvent.VK_ENTER)
{
try
{
showDir();
}
catch (Exception ex)
{
}
}
}
});
}
private void showDir() throws Exception
{
ta.setText("");
String url = tf.getText();
int index1 = url.indexOf("//")+2;
int index2 = url.indexOf("/",index1);
String str = url.substring(index1,index2);
String[] arr = str.split(":");
String host = arr[0];
int port = Integer.parseInt(arr[1]);
String path = url.substring(index2);
//ta.setText(host+"-------"+path);
Socket s = new Socket(host,port);
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
out.println("GET "+path+" HTTP/1.1");
out.println("Host: "+host+":"+port);
out.println("Connection: closed");
out.println("Accept: */*");
out.println("Accept-Encoding: gzip, deflate");
out.println();
out.println();
BufferedReader bufr = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = null;
while ((line=bufr.readLine())!=null)
{
ta.append(line+"\r\n");
}
s.close();
}
public static void main(String[] args)
{
new GUIBrowser();
}
} |
|