【汇智学堂】基于Socket的JAVA版浏览器

在这里插入图片描述

/*
需要打开上一个例子的服务器才能正常运行。
 */
package com.huizhi;

import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;

public class SimpleBrowser extends JFrame implements ActionListener{

    JToolBar toolBar;
    JButton addButton;
    JTextArea textArea;
    JTextField addrFiled;

    SimpleBrowser(){
        addButton=new JButton("地址");
        addrFiled=new JTextField(100);
        textArea=new JTextArea(50,100);
        textArea.setEnabled(false);

        toolBar=new JToolBar();
        toolBar.add(addButton);
        toolBar.add(addrFiled);

        add("North",toolBar);
        add("Center",textArea);

        addrFiled.addActionListener(this);
        setTitle("浏览器");
        setBounds(100,100,500,400);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e){
        System.out.println("ok");
        String addr=addrFiled.getText();

        try{

            StringTokenizer s=new StringTokenizer(addr,":/");
            String protocol=s.nextToken();
            String host=s.nextToken();
            String port=s.nextToken();
            String file=s.nextToken();

            System.out.println("addr");

            System.out.println(protocol+"-"+host+"-"+port+"-"+file);
            Socket socket=new Socket(host,Integer.parseInt(port));

            OutputStream os=socket.getOutputStream();

            PrintWriter out=new PrintWriter(socket.getOutputStream(),true);
            BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));

            //out.println("Get /"+file+" HTTP/1.1");
            out.println("GET /"+file+" HTTP/1.1");
           // out.flush();

            char[] data=new char[1024];
            while (true){
                if(br.ready()){
                    int i=br.read(data);
                    break;
                }
            }
            br.close();
            textArea.setText(new String(data));
            socket.close();

        }
        catch (Exception e1){
            e1.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // write your code here
         new SimpleBrowser();
    }

}



发布了268 篇原创文章 · 获赞 47 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_39593940/article/details/103468335