java语言进阶2

一、java网络

01.基本概念

①ip:定位电脑(定位一个节点,计算机、路由、通信设备)
②端口:区分电脑上软件 公认端口0-1023  注册端口1024-49151 动态、私有端口49152-6535
8080 tomcat 1521 Oracle 3306 Mysql
netstat -ano 查看电脑端口占用cmd命令 netstat -ano|findstr "5535" 对应端口被那个进程站领
③url:区分软件上的资源(统一资源定位符)
④协议:电脑之间交流的方式 传输层协议:    http
http://www.baidu.com:80/index.html
协议      IP地址 (默认)端口  资源名     键值对  #锚点(同一个页面、网站定位)
udp(无连接高效写信)套接字:应用层套接传输层(Socket) 使用数据包接收发送
tcp(面向连接安全打电话三次握手) 客户端+服务器  (用输入输出流连接)
⑤区分资源(html http)
⑥目的:写底层连接
bs:浏览器
cs:局域网
⑦域名:DNS将ip地址转换成字符串
⑧爬虫:
seo:搜索自己公司信息
sem:广告
1.URL  2.下载  3.分析(正则发现规律)  4.存储
html  标签  Css  美化  js 动态

1.IP地址

package com.ws.net;

import java.net.InetAddress;
import java.net.UnknownHostException;

/*
计算机ip
定位电脑
 */
public class TextNextIP {
     
    public static void main(String[] args) {
     
        try {
     
            //使用getLocalHost方法创建inetAddress对象
            InetAddress adder=InetAddress.getLocalHost();
            System.out.println(adder.getHostName());//返回计算机名字
            System.out.println(adder.getHostAddress());//返回本机ip地址
            //根据域名得到netAddress对象
            adder=InetAddress.getByName("www.163.com");
            System.out.println(adder.getHostName());
            System.out.println(adder.getHostAddress());

        } catch (UnknownHostException e) {
     
            e.printStackTrace();
        }
    }
}

2.端口

package com.ws.net;

import java.net.InetSocketAddress;

/*
端口
区分电脑上软件
 */
public class TextNetDuanKou {
     
    public static void main(String[] args) {
     
        InetSocketAddress socketAddress=new InetSocketAddress("117.161.120.40",8080);//地址和端口
        System.out.println(socketAddress.getHostName());//名字
        System.out.println(socketAddress.getAddress());//地址
        System.out.println(socketAddress.getPort());//端口
    }
}

3.URL

package com.ws.net;

import java.net.MalformedURLException;
import java.net.URL;

/*
URL
区分软件上资源,指针
http://www.baidu.com:80/index.html
协议      IP地址      端口  资源名     键值对  #锚点(同一个页面、网站定位)
 */
public class TextNetURL {
     
    public static void main(String[] args) {
     
        try {
     
            URL url=new URL("http://www,baidu.com:80");
            System.out.println("协议:"+url.getProtocol());
            System.out.println("ip:"+url.getHost());
            System.out.println("端口:"+url.getPort());
            System.out.println("请求资源:"+url.getFile());
            System.out.println("参数:"+url.getQuery());
            System.out.println("锚点:"+url.getRef());
        } catch (MalformedURLException e) {
     
            e.printStackTrace();
        }
    }
}

4.爬虫原理

package com.ws.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/*
网络爬虫原理+模拟浏览器
 */
public class TextNetPaChong {
     
    public static void main(String[] args) {
     
        //获取URL
        URL url= null;
        try {
     
            url = new URL("http://www.jd.com");
        } catch (MalformedURLException e) {
     
            e.printStackTrace();
        }
        //下载资源
        try {
     
           /* HttpURLConnection conn=(HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("");
            */
            InputStream is=url.openStream();
            // BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream,"UTF-8"));
            BufferedReader br=new BufferedReader(new InputStreamReader(is,"UTF-8"));
            String msg=null;
            while(null!=(msg=br.readLine()))
                System.out.println(msg);
            br.close();
        } catch (IOException e) {
     
            e.printStackTrace();
        }
    }
}

5.传输协议

①UDP

(1)数据包发送
package com.ws.net;

import java.io.IOException;
import java.net.*;

/*
发送端
1.DatagramSocket指定端口创建接发送端
2.准备数据,转换成字节数组
3.封装成DatagramPacket包裹,指定目的地
4.发送包裹send(DatagramPacket p)到目的地
5.释放资源资源
 */
public class TextNetSocketUDPFaSong04 {
     
    public static void main(String[] args) throws IOException {
     
        System.out.println("发送方启动中");
        //1.DatagramSocket指定端口创建接发送端
        DatagramSocket duankou=new DatagramSocket(6666);
        //2.准备数据,转换成字节数组
        String data="接收端,你好";
        byte datas[]=data.getBytes();
        //3.封装成DatagramPacket包裹,指定目的地
        DatagramPacket packet=new DatagramPacket(datas,0,datas.length,
                new InetSocketAddress(InetAddress.getLocalHost().getHostAddress(),9999));
        //4.发送包裹send(DatagramPacket p)到目的地
        duankou.send(packet);
       // 5.释放资源资源
        duankou.close();

    }
}
package com.ws.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/*
接收端
UDP协议
数据包接收发送套接字(应用层接传输层)
1.DatagramSocket指定端口创建接收端
2.准备容器封装成DaragramPacket包裹
3.阻塞式接收包裹trceive(DatagramPacket p)
4.分析数据
5.释放资源
 */
public class TextNetSocketUDPJeiShou04 {
     
    public static void main(String[] args) throws IOException {
     
        System.out.println("接收方启动中");
        //1.DatagramSocket指定端口创建接收端
        DatagramSocket jeishou=new DatagramSocket(9999);
        //2.准备容器封装成DaragramPacket包裹
        byte data[]=new byte[1024];
        DatagramPacket baocun=new DatagramPacket(data,0,data.length);
        //3.阻塞式接收包裹trceive(DatagramPacket p)
        jeishou.receive(baocun);//阻塞式
        //4.分析数据
        byte datas[]=baocun.getData();
        int len=baocun.getLength();
        System.out.println(new String(datas,0, len));
        //5.释放资源
        jeishou.close();
    }
}
package com.ws.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

/*
发送端
1.DatagramSocket指定端口创建接发送端
2.准备数据,转换成字节数组
3.封装成DatagramPacket包裹,指定目的地
4.发送包裹send(DatagramPacket p)到目的地
5.释放资源资源
 */
public class TextNetSocketUDPFaSong04 {
     
    public static void main(String[] args) throws IOException {
     
        System.out.println("发送方启动中");
        //1.DatagramSocket指定端口创建接发送端
        DatagramSocket duankou=new DatagramSocket(6666);
        //2.准备数据,转换成字节数组
        BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
        while (true) 
        {
     
            String data = reader.readLine();
            byte datas[] = data.getBytes();
            //3.封装成DatagramPacket包裹,指定目的地
            DatagramPacket packet = new DatagramPacket(datas, 0, datas.length,
                    new InetSocketAddress(InetAddress.getLocalHost().getHostAddress(), 9999));
            //4.发送包裹send(DatagramPacket p)到目的地
            duankou.send(packet);
            if(data.equals("结束"))
                break;
        }
       // 5.释放资源资源
        duankou.close();

    }
}
package com.ws.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/*
接收端
UDP协议
数据包接收发送套接字(应用层接传输层)
1.DatagramSocket指定端口创建接收端
2.准备容器封装成DaragramPacket包裹
3.阻塞式接收包裹trceive(DatagramPacket p)
4.分析数据
5.释放资源
 */
public class TextNetSocketUDPJeiShou04 {
     
    public static void main(String[] args) throws IOException {
     
        System.out.println("接收方启动中");
        //1.DatagramSocket指定端口创建接收端
        DatagramSocket jeishou=new DatagramSocket(9999);
        //2.准备容器封装成DaragramPacket包裹
        while (true)
        {
     
            byte data[] = new byte[1024];
            DatagramPacket baocun = new DatagramPacket(data, 0, data.length);
            //3.阻塞式接收包裹trceive(DatagramPacket p)
            jeishou.receive(baocun);//阻塞式
            //4.分析数据
            byte datas[] = baocun.getData();
            int len = baocun.getLength();
            String shuchude=new String(datas, 0, len);
            System.out.println(shuchude);
            if(shuchude.equals("结束"))
                break;
        }
        //5.释放资源
        jeishou.close();
    }
}
package com.ws.net.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

//接收端
public class TextNetUDFJeiShou04Two implements Runnable{
     
   private DatagramSocket jeishou;//1.DatagramSocket指定端口创建接收端

   public TextNetUDFJeiShou04Two(int port)
   {
     
       try {
     
           jeishou =new DatagramSocket(port);
       } catch (SocketException e) {
     
           e.printStackTrace();
       }
   }
    @Override
    public void run() {
     
        while (true) {
     
            //2.准备容器封装成DaragramPacket包裹
            byte data[] = new byte[1024];
            DatagramPacket baocun = new DatagramPacket(data, 0, data.length);
            //3.阻塞式接收包裹trceive(DatagramPacket p)
            try {
     
                jeishou.receive(baocun);//阻塞式
            } catch (IOException e) {
     
                e.printStackTrace();
            }
            //4.分析数据
            byte datas[] = baocun.getData();
            int len = baocun.getLength();
            String shuchude = new String(datas, 0, len);
            System.out.println(shuchude);
            if (shuchude.equals("结束"))
                break;
        }
        //5.释放资源
        jeishou.close();
    }
}
package com.ws.net.udp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
//发送端
class TextNetUDFFaSong04Tuo implements Runnable{
     
    private DatagramSocket duankou= null; //1.DatagramSocket指定端口创建接发送端
    private BufferedReader reader;//2.准备数据,转换成字节数组
    private int port;//发送端口
    private String toIP;
    private int toPort;
    public TextNetUDFFaSong04Tuo(int port,String toIP,int toPort)
    {
     
        this.port=port;
        this.toIP=toIP;
        this.toPort=toPort;
        try {
     
            duankou = new DatagramSocket(port);
            reader =new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
     
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
     
        while (true)
        {
     
            String data = null;
            try {
     
                data = reader.readLine();
            } catch (IOException e) {
     
                e.printStackTrace();
            }
            byte datas[] = data.getBytes();
            //3.封装成DatagramPacket包裹,指定目的地
            DatagramPacket packet = null;
            packet = new DatagramPacket(datas, 0, datas.length,
                    new InetSocketAddress(this.toIP, this.toPort));
            //4.发送包裹send(DatagramPacket p)到目的地
            try {
     
                duankou.send(packet);
            } catch (IOException e) {
     
                e.printStackTrace();
            }
            if(data.equals("结束"))
                break;
        }
        // 5.释放资源资源
        duankou.close();
    }
}
package com.ws.net.udp;

import java.net.InetAddress;
import java.net.UnknownHostException;

/*
多线程实现交流
 */
public class Student {
     
    public static void main(String[] args) throws UnknownHostException {
     
        System.out.println("学生");
        InetAddress adder=InetAddress.getLocalHost();
        String toIp=adder.getHostAddress();
        new Thread(new TextNetUDFFaSong04Tuo(7777,toIp,9999)).start();//发送
        new Thread(new TextNetUDFJeiShou04Two(8888)).start();//接收



    }
}
ackage com.ws.net.udp;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class Teacher{
     
    public static void main(String[] args) throws UnknownHostException {
     
        System.out.println("老师");
        InetAddress adder=InetAddress.getLocalHost();
        String toIp=adder.getHostAddress();
        new Thread(new TextNetUDFFaSong04Tuo(5555,toIp,8888)).start();//发送
        new Thread(new TextNetUDFJeiShou04Two(9999)).start();



    }
}

②UTP

(1)客户服务器连接
package com.ws.net.tcp;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/*
创建服务器
1.指定端口 使用SeverSocket创建服务器
2.阻塞式等待连接 accept
3.操作:输入输出流
4.释放资源
 */
public class TextNetSever04 {
     
    public static void main(String[] args) throws IOException {
     
        InetAddress adder= InetAddress.getLocalHost();
        System.out.println(adder.getHostAddress());//返回本机ip地址
        //1.指定端口 使用SeverSocket创建服务器
        ServerSocket sever=new ServerSocket(8888);
        //2.阻塞式等待连接 accept
        Socket client =sever.accept();
        System.out.println("一个客户建立了连接");
        //3.操作:输入输出流
        DataInputStream dis=new DataInputStream(client.getInputStream());
        String data=dis.readUTF();
        System.out.println(data);
        //4.释放资源
        dis.close();
        client.close();
        sever.close();
    }
}
package com.ws.net.tcp;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/*
创建客户端
1.建立连接:使用Socket创建客户端+服务器的地址端口
2.操作:输入输出操作
3.释放资源
 */
public class TextNetKeHu {
     
    public static void main(String[] args) throws IOException {
     
        InetAddress adder= InetAddress.getLocalHost();
        System.out.println(adder.getHostAddress());//返回本机ip地址
        //1.建立连接:使用Socket创建客户端+服务器的地址端口
        Socket client=new Socket(adder.getHostAddress(),8888);
        //2.操作:输入输出操作
        DataOutputStream dos=new DataOutputStream(client.getOutputStream());
        String data="你好,服务器";
        dos.writeUTF(data);
        dos.flush();
        //3.释放资源
        dos.close();
    }

}
package com.ws.net.tcp;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/*
创建客户端
1.建立连接:使用Socket创建客户端+服务器的地址端口
2.操作:输入输出操作
3.释放资源
 */
public class TextNetKeHu {
     
    public static void main(String[] args) throws IOException {
     
        InetAddress adder= InetAddress.getLocalHost();
        System.out.println(adder.getHostAddress());//返回本机ip地址
        //1.建立连接:使用Socket创建客户端+服务器的地址端口
        Socket client=new Socket(adder.getHostAddress(),8888);
        //2.操作:输入输出操作
        DataOutputStream dos=new DataOutputStream(client.getOutputStream());
        String data="你好,服务器";
        dos.writeUTF(data);
        dos.flush();
        //3.释放资源
        dos.close();
    }

}
(2)文件上传
package com.ws.net.tcp;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/*
创建客户端
1.建立连接:使用Socket创建客户端+服务器的地址端口
2.操作:输入输出操作
3.释放资源
 */
public class TextNetKeHu04 {
     
    public static void main(String[] args) throws IOException {
     
        InetAddress adder= InetAddress.getLocalHost();
        System.out.println(adder.getHostAddress());//返回本机ip地址
        /*BufferedReader shuru=new BufferedReader(new InputStreamReader(System.in));//输入
        System.out.println("输入用户名");
        String name=shuru.readLine();
        System.out.println("输入密码");
        String pwd=shuru.readLine();

         */
        //1.建立连接:使用Socket创建客户端+服务器的地址端口
        Socket client=new Socket(adder.getHostAddress(),8888);
        //2.操作:输入输出操作
        /*DataOutputStream dos=new DataOutputStream(client.getOutputStream());
        dos.writeUTF("name="+name+"&"+"pwd="+pwd);
        dos.flush();
        //双向
        DataInputStream dis=new DataInputStream(client.getInputStream());
        String data=dis.readUTF();
        System.out.println(data);

         */
        InputStream is=new BufferedInputStream(new FileInputStream("E:/java语言/javaNet/src/com/ws/net/tcp/11.jpg"));
        OutputStream os=new BufferedOutputStream(client.getOutputStream());
        byte flush[]=new byte[1024];
        int len=-1;
        while ((len=is.read(flush))!=-1)
            os.write(flush,0,len);
        os.flush();
        //3.释放资源
        //dos.close();
        os.close();
        is.close();
        client.close();
    }

}
package com.ws.net.tcp;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/*
创建服务器
1.指定端口 使用SeverSocket创建服务器
2.阻塞式等待连接 accept
3.操作:输入输出流
4.释放资源
 */
public class TextNetSever04 {
     
    public static void main(String[] args) throws IOException {
     
        InetAddress adder= InetAddress.getLocalHost();
        System.out.println(adder.getHostAddress());//返回本机ip地址
        //1.指定端口 使用SeverSocket创建服务器
        ServerSocket sever=new ServerSocket(8888);
        //2.阻塞式等待连接 accept
        Socket client =sever.accept();
        //System.out.println("一个客户建立了连接");
        //3.操作:输入输出流

        /*DataInputStream dis=new DataInputStream(client.getInputStream());
        String data=dis.readUTF();
        String name="";
        String pwd="";
        //分析
        String dataArray[]=data.split("&");
        for(String in:dataArray)
        {
            String fo[]=in.split("=");
            if(fo[0].equals("name"))
            {
                System.out.println("你的用户名为:"+fo[1]);
                name=fo[1];
            }
            else if(fo[0].equals("pwd"))
            {
                System.out.println("你的密码为:"+fo[1]);
                pwd=fo[1];
            }
        }
        //双向
        DataOutputStream dos=new DataOutputStream(client.getOutputStream());
        if(name.equals("wangshuo")&&pwd.equals("1212"))
        {
            dos.writeUTF("登录成功");
        }
        else
        {
            dos.writeUTF("用户名或密码错误");


         */
        InputStream is=new BufferedInputStream(client.getInputStream());
        OutputStream os=new BufferedOutputStream(new FileOutputStream("E:/java语言/javaNet/src/com/ws/net/tcp/tcp.jpg"));
        byte flush[]=new byte[1024];
        int len=-1;
        while ((len=is.read(flush))!=-1)
            os.write(flush,0,len);
        //4.释放资源
        //dis.close();
        client.close();
        //sever.close();//关闭数据库
    }
}
(3)封装
package com.ws.net.tcp;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/*
创建服务器
1.指定端口 使用SeverSocket创建服务器
2.阻塞式等待连接 accept
3.操作:输入输出流
4.释放资源
 */
public class Sever04 {
     
    public static void main(String[] args) throws IOException {
     
        InetAddress adder = InetAddress.getLocalHost();
        System.out.println(adder.getHostAddress());//返回本机ip地址
        //1.指定端口 使用SeverSocket创建服务器
        ServerSocket sever = new ServerSocket(8888);
        boolean isSever=true;
        //2.阻塞式等待连接 accept
        while (isSever)
        {
     
            Socket client = sever.accept();
            System.out.println("一个客户建立了连接");
            new Thread(new Fu(client)).start();
        }
            //sever.close();//关闭数据库
        }
}
class Fu implements Runnable
{
     
    private DataInputStream dis;
    private DataOutputStream dos;
    private Socket client;

    public Fu(Socket clinet) {
     
        this.client=clinet;
        //输入流
        try {
     
            dis=new DataInputStream(clinet.getInputStream());
            dos=new DataOutputStream(clinet.getOutputStream());
        } catch (IOException e) {
     
            e.printStackTrace();
            release();
        }
        //输出流
    }
    @Override
    public void run() {
     

        String name = "";
        String pwd = "";
        //分析
        String[] dataArray = recrive().split("&");
        for (String in : dataArray) {
     
            String fo[] = in.split("=");
            if (fo[0].equals("name")) {
     
                System.out.println("你的用户名为:" + fo[1]);
                name = fo[1];
            } else if (fo[0].equals("pwd")) {
     
                System.out.println("你的密码为:" + fo[1]);
                pwd = fo[1];
            }
        }
        //双向
        if (name.equals("wangshuo") && pwd.equals("1212")) {
     
            send("登录成功");
        } else {
     
            send("用户名或密码错误");
        }
    }
    //释放资源
    private void release()
    {
     
        try {
     
            if(null!=dos||null!=dis||null!=client)
            {
     
                dos.flush();
                dis.close();
                client.close();
            }
        } catch (IOException e) {
     
            e.printStackTrace();
        }
    }
    //接收数据
    private String recrive()
    {
     
        //3.操作:输入输出流
        String data = "";
        try {
     
            data = dis.readUTF();
        } catch (IOException e) {
     
            e.printStackTrace();
        }
        return data;
    }
    //发送数据
    private void send(String msg)
    {
     
        try {
     
            dos.writeUTF(msg);
            dos.close();
        } catch (IOException e) {
     
            e.printStackTrace();
        }

    }
}
package com.ws.net.tcp;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/*
创建客户端
1.建立连接:使用Socket创建客户端+服务器的地址端口
2.操作:输入输出操作
3.释放资源
 */
public class KeHu04 {
     
    public static void main(String[] args) throws IOException {
     
        InetAddress adder= InetAddress.getLocalHost();
        System.out.println(adder.getHostAddress());//返回本机ip地址



        //1.建立连接:使用Socket创建客户端+服务器的地址端口
        Socket client=new Socket(adder.getHostAddress(),8888);
        //2.操作:输入输出操作
        //发送数据
        new send(client).send();
        //双向接收数据
        new receive(client).receive();
        //3.释放资源
        client.close();
    }
    //发送数据
    static class send
    {
     
        private Socket client;
        private DataOutputStream dos;
        private BufferedReader shuru;
        private String msg;
        public send(Socket client) throws IOException {
     
            this.client=client;
            shuru=new BufferedReader(new InputStreamReader(System.in));
            this.msg=init();
            dos=new DataOutputStream(client.getOutputStream());
        }
        public void send() throws IOException {
     
            dos.writeUTF(msg);
            dos.flush();
        }
        private String init() throws IOException {
     
            System.out.println("输入用户名");
            String name=shuru.readLine();
            System.out.println("输入密码");
            String pwd=shuru.readLine();
            return "name="+name+"&"+"pwd="+pwd;
        }
    }
    //读取数据
    static class receive
    {
     
        private Socket client;
        private DataInputStream dis;
        public receive(Socket client) throws IOException {
     
            this.client=client;
            dis=new DataInputStream(client.getInputStream());
        }
        public void  receive() throws IOException {
     
            String data=dis.readUTF();
            System.out.println(data);
        }
    }

}

02.在线聊天室

①单人

package com.ws.net.LiaoTian;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
/*
在线聊天室客户端
 */
public class Client {
     
    public static void main(String[] args) throws IOException {
     
        InetAddress adder= InetAddress.getLocalHost();
        System.out.println("客户"+adder.getHostAddress());//返回本机ip地址
        //1.建立连接:使用Socket创建客户端+服务器的地址端口
        Socket client=new Socket(adder.getHostAddress(),1212);
        //2.操作:发送消息
        new Thread(new Send(client)).start();
        //接收消息
        new Thread(new Receive(client)).start();
    }
}
package com.ws.net.LiaoTian;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
//接收端封装客户端
public class Receive implements Runnable{
     
    private DataInputStream dis;
    private Socket client;
    private boolean is;
    public Receive(Socket client)
    {
     
        this.is=true;
        this.client=client;
        try {
     
            dis=new DataInputStream(client.getInputStream());
        } catch (IOException e) {
     
            this.release();
        }

    }
    //接收消息
    private String receive()
    {
     
        String msg="";
        try {
     
            msg=dis.readUTF();
        } catch (IOException e) {
     
            System.out.println("==========接收============");
            this.release();
        }
        return msg;
    }
    @Override
    public void run() {
     
        while (is)
        {
     
            String msg=receive();
            if(!msg.equals(""))
                System.out.println(msg);
        }

    }
    private void release()
    {
     
        this.is=false;
        SxtUtils.close(dis,client);
    }
}
package com.ws.net.LiaoTian;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

//发送端封装客户端
public class Send implements Runnable{
     
    private  BufferedReader console;
    private  DataOutputStream dos;
    private Socket client;
    private boolean is;
    @Override
    public void run() {
     
        while (is)
        {
     
            String msg=get();
            if(!msg.equals(""))
            {
     
                send(msg);
            }
        }

    }
    //发送消息
    private void send(String msg)
    {
     
        try {
     
            dos.writeUTF(msg);
            dos.flush();
        } catch (IOException e) {
     
            this.release();
        }

    }
    public Send(Socket client)
    {
     
        this.is=true;
        this.client=client;
        console=new BufferedReader(new InputStreamReader(System.in));
        try {
     
            dos=new DataOutputStream(client.getOutputStream());
        } catch (IOException e) {
     
            this.release();
        }
    }
    //释放资源
    private void release()
    {
     
        this.is=false;
        SxtUtils.close(dos,client);
    }
    //获取消息
    private String get()
    {
     
        try {
     
            return console.readLine();
        } catch (IOException e) {
     
            this.release();
        }
        return "";
    }
}
package com.ws.net.LiaoTian;

import java.io.Closeable;
import java.io.IOException;

//工具类
public class SxtUtils {
     
    public static void close(Closeable ... targets){
     
        for(Closeable ta:targets)
        {
     
            try {
     
                if(null!=ta)
                    ta.close();
            }
            catch (Exception e)
            {
     

            }
        }
    }
}
package com.ws.net.LiaoTian;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/*
在线聊天室,服务端
 */
public class Chat {
     
    public static void main(String[] args) throws IOException {
     
        InetAddress adder = InetAddress.getLocalHost();
        System.out.println(adder.getHostAddress());//返回本机ip地址
        //1.指定端口 使用SeverSocket创建服务器
        ServerSocket sever = new ServerSocket(1212);
        boolean isk = true;
        while (isk)
        {
     
            //2.阻塞式等待连接 accept
            Socket client = sever.accept();
            System.out.println("一个客户建立了连接");
            new Thread(new Channel(client)).start();

        }
        //sever.close();//关闭数据库
    }
    //一个客户一个
    static class Channel implements Runnable
    {
     
        private DataInputStream dis;

        private DataOutputStream dos;
        private Socket client;
        private boolean is;
        @Override
        public void run() {
     
            while (is)
            {
     
                String msg=receive();
                if(!msg.equals(""))
                    send(msg);
            }
        }
        //接收消息
        public Channel(Socket client)
        {
     
            this.client=client;
            is=true;
            try
            {
     
            dis=new DataInputStream(client.getInputStream());
            dos = new DataOutputStream(client.getOutputStream());
            }
            catch (IOException e)
            {
     
                release();

            }
        }
        //接收消息
        private String receive()
        {
     
            String msg="";
            try {
     
                msg=dis.readUTF();
            } catch (IOException e) {
     
               release();
            }
            return msg;
        }
        //发送消息
        private void send(String msg)
        {
     
            try {
     
                dos.writeUTF(msg);
                dos.flush();
            } catch (IOException e) {
     
                release();
            }
        }
        //释放资源
        private void release(){
     
            SxtUtils.close(dis,dos,client);
        }
    }
}

②群聊+私聊

package com.ws.net.LiaoTian;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/*
在线聊天室,服务端
 */
public class Chat {
     
    //容器
    private static CopyOnWriteArrayList<Channel> all = new CopyOnWriteArrayList<Channel>();

    public static void main(String[] args) throws IOException {
     
        InetAddress adder = InetAddress.getLocalHost();
        System.out.println(adder.getHostAddress());//返回本机ip地址
        //1.指定端口 使用SeverSocket创建服务器
        ServerSocket sever = new ServerSocket(1212);
        boolean isk = true;
        while (isk) {
     
            //2.阻塞式等待连接 accept
            Socket client = sever.accept();
            System.out.println("一个客户建立了连接");
            Channel c = new Channel(client);//客户
            all.add(c);//管理所有成员
            new Thread(c).start();

        }
        //sever.close();//关闭数据库
    }

    //一个客户一个
    static class Channel implements Runnable {
     
        private DataInputStream dis;
        private String name;
        private DataOutputStream dos;
        private Socket client;
        private boolean is;

        @Override
        public void run() {
     
            while (is) {
     
                String msg = receive();
                if (!msg.equals(""))
                    sendQun(msg, false);//发给他人
            }
        }

        //接收消息
        public Channel(Socket client) {
     
            this.client = client;
            try {
     
                dis = new DataInputStream(client.getInputStream());
                dos = new DataOutputStream(client.getOutputStream());
                is = true;
                //获取名称
                this.name = receive();
                //欢迎
                this.send("欢迎你到来");
                sendQun(this.name + "来到了聊天室", true);
            } catch (IOException e) {
     
                release();

            }
        }

        //接收消息
        private String receive() {
     
            String msg = "";
            try {
     
                msg = dis.readUTF();
            } catch (IOException e) {
     
                release();
            }
            return msg;
        }

        //群聊,获取自己的消息发给其他人
        //私聊 约定数据格式 @xxx:msg
        private void sendQun(String msg, boolean isSys) {
     
            boolean isSi = msg.startsWith("@");
            if (isSi) {
     //私聊
                int idx=msg.indexOf(":");
                //获取目标和数据
                String siname=msg.substring(1,idx);
                msg=msg.substring(idx+1);
                for(Channel ren:all)
                {
     
                    if(ren.name.equals(siname))//找到目标
                    {
     
                        ren.send(this.name+"对你说:"+msg);//私聊消息
                    }
                }
            } else {
     
                for (Channel ren : all) {
     
                    if (ren == this) {
     
                        continue;
                    }
                    if (!isSys) {
     
                        ren.send(this.name + "对所有人说:" + msg);//发给其他人
                    } else {
     
                        ren.send(msg);//系统消息
                    }
                }
            }
        }

        //发送消息
        private void send(String msg) {
     
            try {
     
                dos.writeUTF(msg);
                dos.flush();
            } catch (IOException e) {
     
                release();
            }
        }

        //释放资源
        private void release() {
     
            this.is = false;
            SxtUtils.close(dis, dos, client);
            //退出
            all.remove(this);
            sendQun(this.name + "离开了群聊", true);
        }
    }
}
package com.ws.net.LiaoTian;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
//接收端封装客户端
public class Receive implements Runnable{
     
    private DataInputStream dis;
    private Socket client;
    private boolean is;
    public Receive(Socket client)
    {
     
        this.is=true;
        this.client=client;
        try {
     
            dis=new DataInputStream(client.getInputStream());
        } catch (IOException e) {
     
            this.release();
        }

    }
    //接收消息
    private String receive()
    {
     
        String msg="";
        try {
     
            msg=dis.readUTF();
        } catch (IOException e) {
     
            System.out.println("==========接收============");
            this.release();
        }
        return msg;
    }
    @Override
    public void run() {
     
        while (is)
        {
     
            String msg=receive();
            if(!msg.equals(""))
                System.out.println(msg);
        }

    }
    private void release()
    {
     
        this.is=false;
        SxtUtils.close(dis,client);
    }
}
package com.ws.net.LiaoTian;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
//接收端封装客户端
public class Receive implements Runnable{
     
    private DataInputStream dis;
    private Socket client;
    private boolean is;
    public Receive(Socket client)
    {
     
        this.is=true;
        this.client=client;
        try {
     
            dis=new DataInputStream(client.getInputStream());
        } catch (IOException e) {
     
            this.release();
        }

    }
    //接收消息
    private String receive()
    {
     
        String msg="";
        try {
     
            msg=dis.readUTF();
        } catch (IOException e) {
     
            System.out.println("==========接收============");
            this.release();
        }
        return msg;
    }
    @Override
    public void run() {
     
        while (is)
        {
     
            String msg=receive();
            if(!msg.equals(""))
                System.out.println(msg);
        }

    }
    private void release()
    {
     
        this.is=false;
        SxtUtils.close(dis,client);
    }
}
package com.ws.net.LiaoTian;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
//接收端封装客户端
public class Receive implements Runnable{
     
    private DataInputStream dis;
    private Socket client;
    private boolean is;
    public Receive(Socket client)
    {
     
        this.is=true;
        this.client=client;
        try {
     
            dis=new DataInputStream(client.getInputStream());
        } catch (IOException e) {
     
            this.release();
        }

    }
    //接收消息
    private String receive()
    {
     
        String msg="";
        try {
     
            msg=dis.readUTF();
        } catch (IOException e) {
     
            System.out.println("==========接收============");
            this.release();
        }
        return msg;
    }
    @Override
    public void run() {
     
        while (is)
        {
     
            String msg=receive();
            if(!msg.equals(""))
                System.out.println(msg);
        }

    }
    private void release()
    {
     
        this.is=false;
        SxtUtils.close(dis,client);
    }
}
package com.ws.net.LiaoTian;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
//接收端封装客户端
public class Receive implements Runnable{
     
    private DataInputStream dis;
    private Socket client;
    private boolean is;
    public Receive(Socket client)
    {
     
        this.is=true;
        this.client=client;
        try {
     
            dis=new DataInputStream(client.getInputStream());
        } catch (IOException e) {
     
            this.release();
        }

    }
    //接收消息
    private String receive()
    {
     
        String msg="";
        try {
     
            msg=dis.readUTF();
        } catch (IOException e) {
     
            System.out.println("==========接收============");
            this.release();
        }
        return msg;
    }
    @Override
    public void run() {
     
        while (is)
        {
     
            String msg=receive();
            if(!msg.equals(""))
                System.out.println(msg);
        }

    }
    private void release()
    {
     
        this.is=false;
        SxtUtils.close(dis,client);
    }
}
package com.ws.net.LiaoTian;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
//接收端封装客户端
public class Receive implements Runnable{
     
    private DataInputStream dis;
    private Socket client;
    private boolean is;
    public Receive(Socket client)
    {
     
        this.is=true;
        this.client=client;
        try {
     
            dis=new DataInputStream(client.getInputStream());
        } catch (IOException e) {
     
            this.release();
        }

    }
    //接收消息
    private String receive()
    {
     
        String msg="";
        try {
     
            msg=dis.readUTF();
        } catch (IOException e) {
     
            System.out.println("==========接收============");
            this.release();
        }
        return msg;
    }
    @Override
    public void run() {
     
        while (is)
        {
     
            String msg=receive();
            if(!msg.equals(""))
                System.out.println(msg);
        }

    }
    private void release()
    {
     
        this.is=false;
        SxtUtils.close(dis,client);
    }
}

二、javaWebserver

01.基本概念

①客户请求界面->服务器响应内容->响应内容是根据每个web动态产生的->内部启动多个线程产生不同内容
②请求响应的交互给予Http协议

一、反射(Reflection):java一个类中的各种结构(方法、属性、构造器、类名)映射成一个个java对象
1.获取类的Class对象
三种获取方式: //1.对象.getClass()   //2.类.class     常用://3.Class.forName("包名.类名)
2.动态创建对象
clas.getConstructor().newInstance()

二、XML:可扩展标记语言:数据的一种存储格式/存储软件的参数
目的:程序解析此配置文件,达到不修改代码就改程序的
XML的SAX解析:
1.获取解析工厂
2.熊解释工厂获取解析器
3.编写处理器
4.加载文档Document注册处理器
5.解析
6.获取数据

html(骨架)  css(化妆)  js(交互)
三、HTML:超文本标记语言(浏览器的语言)
固定结构:
------开始标签
    网页上的控制信息
       页面标题
    
    页面显示内容
-----结束标签

四、http协议:超文本传输语言(浏览器和服务器交流)(底层是tcp udp)
请求协议+响应协议
1.请求协议
①请求行:方法(CET/POST)、url、协议/版本
②请求头
③请求正文
2.响应协议
①响应行:协议/版本、状态码、状态描述
②响应头
③响应正文

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-su3CewSM-1604825628632)(E:\大学课程作业资料汇总\大二下学期\java\笔记\java高级篇\image-20200913192528460.png)]

1.反射Reflection

package com.ws.Webserver.Reflection;

import java.lang.reflect.InvocationTargetException;

/*
反射:把java的一个类中的各种结构映射成一个个java对象
1.获取类的Class对象
三种获取方式: //1.对象.getClass()   //2.类.class     常用://3.Class.forName("包名.雷名)
2.动态创建对象
clas.getConstructor().newInstance()
 */
public class TextReflection {
     
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
     
        //1.获取类的Class对象

        //三种方式
        //1.对象.getClass()
        Text text=new Text();
        //Class clas=text.getClass();
        //2.类.class
        //clas=Text.class;
        //3.Class.forName("包名.雷名)
        Class clas=Class.forName("com.ws.Webserver.Reflection.Text");

        //2.动态创建对象

        //1.使用方法
        /*Text text2= null;//老版本不推荐
        try {
            text2 = (Text)clas.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        System.out.println(text2);
         */
        //2.使用构造器
        Text text1=(Text)clas.getConstructor().newInstance();
        System.out.println(text1);

    }
}
class Text
{
     
    public Text()
    {
     

    }

}

2.xml的解析

①简单的解析

package com.ws.Webserver.XML;
//要写入数据的类
public class Text {
     
    private String name;
    private  int age;

    public Text() {
     
    }

    public Text(String name) {
     
        this.name = name;
    }

    public String getName() {
     
        return name;
    }

    public void setName(String name) {
     
        this.name = name;
    }

    public int getAge() {
     
        return age;
    }

    public void setAge(int age) {
     
        this.age = age;
    }
}

<persons>
    <person>
        <name>至尊宝name>
        <age>9000age>
    person>
    <person>
        <name>白晶晶name>
        <age>7000age>
    person>
persons>
package com.ws.Webserver.XML;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/*
XML的SAX解析:
1.获取解析工厂
2.熊解释工厂获取解析器
3.编写处理器
4.加载文档Document注册处理器
5.解析
6.获取数据
 */
public class TextXml {
     
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
     
        //XML的SAX解析:
        //1.获取解析工厂
        SAXParserFactory factory=SAXParserFactory.newInstance();
        //2.熊解释工厂获取解析器
        SAXParser parser=factory.newSAXParser();
        //3.编写处理器
        //4.加载文档Document注册处理器
        ChuLi chuLi=new ChuLi();
        //5.解析
        parser.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream("com/ws/Webserver/XML/TextXml.xml"),chuLi);

        //6.获取数据
        List<Text> texts=chuLi.getTexts();
        for (Text t:texts)
        {
     
            System.out.println(t.getName()+"-->"+t.getAge());
        }

    }
}
//xml解析
class ChuLi extends DefaultHandler
{
     
    private List<Text> texts;
    private Text text;
    private String tag;//存储操作的标签
    @Override
    public void startDocument() throws SAXException {
     //文档开始
        System.out.println("解析文档开始");
        texts=new ArrayList<>();
    }

    public List<Text> getTexts() {
     
        return texts;
    }

    public void setTexts(List<Text> texts) {
     
        this.texts = texts;
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
     
        System.out.println(qName+"==>解析开始");
        if(null!=qName)
        {
     
            tag=qName;
            if(qName.equals("person"))
                text=new Text();
        }
    }

    //解析内容
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
     
        String s=new String(ch,start,length).trim();
        if (null!=tag)//处理空的问题
        {
     
            if (s.length() > 0)
                System.out.println("内容为:" + s);
            else
                System.out.println("内容为空");
            if (tag.equals("name"))
                text.setName(s);
            else if (tag.equals("age")) {
     //逐行解析,解决空的问题
                if (s.length() > 0)
                    text.setAge(Integer.valueOf(s));
            }
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
     
        System.out.println(qName+"==>解析结束");
        if(null!=qName) {
     
            if (qName.equals("person"))
                texts.add(text);
        }
        tag=null;
    }

    @Override
    public void endDocument() throws SAXException {
     //文档结束
        System.out.println("解析文档结束");
    }
}

②两个解析

package com.ws.Webserver.XML.tuo;
/*
    
        login
        com.ws.Webserver.XML.tuo.Entity.LoginServlet
    
 */
public class Entity {
     
    private String name;
    private String clz;

    public Entity() {
     
    }

    public String getName() {
     
        return name;
    }

    public void setName(String name) {
     
        this.name = name;
    }

    public String getClz() {
     
        return clz;
    }

    public void setClz(String clz) {
     
        this.clz = clz;
    }
}
package com.ws.Webserver.XML.tuo;

import java.util.HashSet;
import java.util.Set;
/*

        login
        /login
        /g

 */
public class Mapping {
     
    private String name;
    private Set<String> patterns;

    public Mapping() {
     
        patterns=new HashSet<>();
    }
    public void addPattern(String pttern)
    {
     
        this.patterns.add(pttern);
    }

    public String getName() {
     
        return name;
    }

    public void setName(String name) {
     
        this.name = name;
    }

    public Set<String> getPatterns() {
     
        return patterns;
    }

    public void setPatterns(Set<String> patterns) {
     
        this.patterns = patterns;
    }
}

<web-app>
    <servle>
        <servle-name>loginservle-name>
        <servle-class>com.ws.Webserver.XML.tuo.Entity.LoginServletservle-class>
    servle>
    <servle>
        <servle-name>regservle-name>
        <servle-class>com.ws.Webserver.XML.tuo.Mapping.RegisterServletservle-class>
    servle>
    <servle-mapping>
        <servle-name>loginservle-name>
        <url-pattern>/loginurl-pattern>
        <url-pattern>/gurl-pattern>
    servle-mapping>
    <servle-mapping>
        <servle-name>regservle-name>
        <url-pattern>/regurl-pattern>
    servle-mapping>

web-app>
package com.ws.Webserver.XML.tuo;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/*
XML的SAX解析:
1.获取解析工厂
2.熊解释工厂获取解析器
3.编写处理器
4.加载文档Document注册处理器
5.解析
6.获取数据
 */
public class XmlTest{
     
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
     
        //XML的SAX解析:
        //1.获取解析工厂
        SAXParserFactory factory=SAXParserFactory.newInstance();
        //2.熊解释工厂获取解析器
        SAXParser parser=factory.newSAXParser();
        //3.编写处理器
        //4.加载文档Document注册处理器
        WebHandler webHandler=new WebHandler();
        //5.解析
        parser.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream("com/ws/Webserver/XML/tuo/web.xml"),webHandler);

        //6.获取数据
        List<Entity> entitys=webHandler.getEntitys();
        List<Mapping> mappings=webHandler.getMappings();
        System.out.println(entitys.size());
        System.out.println(mappings.size());

    }
}
//xml解析
class WebHandler extends DefaultHandler
{
     
    private List<Entity> entitys;
    private List<Mapping> mappings;
    private Entity entity;
    private Mapping mapping;
    private String tag;//存储操作的标签
    private boolean isMapping=false;
    @Override
    public void startDocument() throws SAXException {
     //文档开始
        //System.out.println("解析文档开始");
        entitys=new ArrayList<>();
        mappings=new ArrayList<>();
    }

    public List<Entity> getEntitys() {
     
        return entitys;
    }

    public List<Mapping> getMappings() {
     
        return mappings;
    }
    //解析文档开始
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
     
        //System.out.println(qName+"==>解析开始");
        if(null!=qName)
        {
     
            tag=qName;//存储标签名
            if(qName.equals("servle")) {
     
                entity = new Entity();
                isMapping=false;
            }
            else if (qName.equals("servle-mapping")) {
     
                mapping = new Mapping();
                isMapping=true;
            }
        }
    }

    //解析内容
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
     
        String s=new String(ch,start,length).trim();
        if (null!=tag)//处理空的问题
        {
     
            if (isMapping)//操作servlet=mapping
            {
     
                if (tag.equals("servle-name"))
                    mapping.setName(s);
                else if (tag.equals("url-pattern")) {
     //逐行解析,解决空的问题
                    mapping.addPattern(s);
                }
            }else //操作servler
            {
     
                /*if (s.length() > 0)
                    System.out.println("内容为:" + s);
                else
                    System.out.println("内容为空");
                 */
                if (tag.equals("servle-name"))
                    entity.setName(s);
                else if (tag.equals("servle-class")) {
     //逐行解析,解决空的问题
                    entity.setClz(s);
                }
            }
        }
    }
    //解析内容结束
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
     
        //System.out.println(qName+"==>解析结束");
        if(null!=qName) {
     
            if (qName.equals("servle"))
                entitys.add(entity);
            else if (qName.equals("servle-mapping"))
                mappings.add(mapping);

            if(qName.equals("servle")) {
     
                entity = new Entity();
                isMapping=false;
            }
            else if (qName.equals("servle-mapping")) {
     
                mapping = new Mapping();
                isMapping=true;
            }
        }
        tag=null;
    }

    @Override
    public void endDocument() throws SAXException {
     //文档结束
        //System.out.println("解析文档结束");
    }
}

③反射解析

Entity
LonginServlet
Mapping
RegisterServlet
Servlet
web.xml
WebContext
XmlTest.java

3.简单的html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>第一个html登录title>
head>
<body>
<h1>表单的使用h1>
<pre>
    post:提交  请求参数url不可见  量大<br/>
    get:默认,获取  请求参数url可见 不安全  量小<br/>
    action:请求web服务器资源 br>
    name:请求服务器,必须存在,数据不能提交<br/>
    id:作为前端使用,区分唯一<br/>
pre>
<form action="" method="post">
    用户名<br/>
    密码<br/>
    
form>
body>
html>

你可能感兴趣的:(网络,java)