java基础 - url & 线程

来源:互联网 发布:帝国cms生成html 编辑:程序博客网 时间:2024/06/05 11:57

将网络上的HTML文件写入到本地一个文件里

    public static void main(String[] args) throws Exception {        URL url=new URL("http://www.qtfy30.cn/");        InputStream is = url.openStream();        OutputStream os =new FileOutputStream("E:/test/tt1.html");        byte[] b=new byte[1024];        int length=0;        //读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1。         while(-1!=(length = is.read(b,0,b.length))){            os.write(b, 0, length);        }        os.flush();        os.close();        is.close();    }

实现客户端和服务器端的网络交互

文件列表:
1. 服务端
2. 客户端
3. 接收器线程

//1.服务端public class SocketService {    public static void main(String[] args) throws Exception {        //socket -网络通信一端的端口   ServerSocket 网络通信服务        ServerSocket ss= new ServerSocket(1000);        // 接收网络通信服务        Socket socket =ss.accept();        //输入流      由通信端口输入        InputStream is =socket.getInputStream();        // 输出流   由通信端口输出        OutputStream os =socket.getOutputStream();        //new一个线程 传入 socket接收信息         new AcceptThread("aa", socket).start();        //接收字节的数组        byte[] buffer = new byte[200];        int length = 0;        //系统输入        Scanner sc = new Scanner(System.in);        String str = null;        //接收console输入的信息 并发送到client端(AcceptThread线程在运行,接收socket的信息)        while(true){            if(sc.hasNext()){                str = sc.nextLine();                String messageString = new String (str.getBytes("GBK")).trim();                os.write(messageString.getBytes());                os.flush();            }        }    }}
//2.客户端public class SocketClientA {    public static void main(String[] args) throws Exception {        Socket socket1 = new Socket("127.0.0.1",1000);        InputStream is = socket1.getInputStream();        OutputStream os = socket1.getOutputStream();        new AcceptThread("aa", socket1).start();        byte[] buffer = new byte[200];        int length = 0;        Scanner sc = new Scanner(System.in);        String str = null;        while(null!=(str=sc.next())){            String messageString = new String (str.getBytes("utf-8"));            os.write(messageString.getBytes());            os.flush();        }        is.close();        os.close();        socket1.close();    }}
//3.接收信息线程public class AcceptThread extends Thread{    private Socket socket;    //构造函数 传入socket     public AcceptThread(String name ,Socket socket){        super (name);        this.socket=socket;    }    //重载 run函数     @Override    public void run(){    super.run();    InputStream is=null;    byte[] b=new byte[200];    int length = 0;    //接收socket 传来的信息    try{        is=socket.getInputStream();        while(-1 != (length=is.read(b, 0, b.length))){            String str=new String (b,0,length);            System.out.println(str);        }    }catch (Exception e){        e.printStackTrace();    }    }}
0 0
原创粉丝点击