Java之网络编程

🍤Java之网络编程


目录:



1、Java.net包下InetAddress此类表示Internet协议(IP)地址。
  • getLocalHost():获取主机名+地址
  • getByName():通过域名获取域名和地址
  • getHostName():获取主机名
  • getHostAddress():获取地址

public class Url07 {
    public static void main(String[] args) throws UnknownHostException {
        System.out.println(InetAddress.getByName("localhost"));//localhost/127.0.0.1
        System.out.println(InetAddress.getLocalHost());//LAPTOP-5TL5RGLT/192.168.5.72
        System.out.println(InetAddress.getLocalHost().getHostName());//LAPTOP-5TL5RGLT
        System.out.println(InetAddress.getLocalHost().getHostAddress());//192.168.5.72
        System.out.println(InetAddress.getByName("localhost").getHostAddress());//127.0.0.1
    }
}

2、Java.net包下InetSocketAddress此类实现IP套字地址(IP+端口号)
  • getPort():获取端口号
  • getName():获取域名
  • getAddress():获取地址

常见端口号:80 http / 8080 Tomcat / 3306 mysql /1521 oracle

  • 互联网三大基石:html、http、URL
  • URL组成:1、协议 2、域名 3、端口号 4、资源
public class Url01 {
    public static void main(String[] args) throws MalformedURLException {
        InetSocketAddress is=new InetSocketAddress("wwww.baidu.com",12345);
        System.out.println(is.getAddress());//wwww.baidu.com/220.181.38.251
        System.out.println(is.getHostName());//wwww.baidu.com
        System.out.println(is.getPort());//12345
        System.out.println("-----------------------------");
        URL ul=new URL("http://www.taobao.com:80//index.html?username=zhangsan&password=123");
        System.out.println(ul.getProtocol());//获取协议http
        System.out.println(ul.getHost());//域名www.taobao.com
        System.out.println(ul.getPort());//多口号80
        System.out.println(ul.getQuery());//获取资源信息username=zhangsan&password=123
        System.out.println(ul.getFile());//index.html?username=zhangsan&password=123
        String[] str=ul.getQuery().split("&");
        System.out.println(Arrays.toString(str));//[username=zhangsan, password=123]
        System.out.println(tool);//localhost/127.0.0.1:1122
    }
}

在这里插入图片描述

3、Socket类和ServerSocket类
  • Class Socket

    所谓socket 通常也称作”套接字“,用于描述IP地址和端口,是一个通信链的句柄。应用程序通常通过”套接字”向网络发出请求或者应答网络请求。
    - 相当于传输层为应用层开辟的小口子
    - 不同的协议对Socket的实现不同
    - 面向Socket编程
    
  • Class ServerSocket

    该类实现服务器套接字。 服务器套接字等待通过网络进入的请求。 它根据该请求执行某些操作,然后可能将结果返回给请求者。 
    

UDP和TCP协议

  • ①UDP协议:实现发送端
    • DatagramSocket:定义发送端与接收端
    • DatagramPacket:定义数据包,封装数据。
  • ②TCP协议:实现基础服务端
    • 数据的传输基于IO
    • 发送数据两端不平等,客户端与服务端
    • Socket客户端 ServerSocket服务端

🍣**案例1:》》》》通过UDP协议实现发送端与接受端的通信**

==发送端代码:==

//发送端
public class Url03 {
    public static void main(String[] args) throws IOException {
        System.out.println("----正在发送----");
        //定义发送端
        DatagramSocket ds=new DatagramSocket(8888);
        //准备数据
        byte[] bs="你好呀!!!!".getBytes();
        //打包数据
        DatagramPacket dp=new DatagramPacket(bs,0,bs.length,new InetSocketAddress("localhost",10000));
        //发送
        ds.send(dp);
        //关闭
        ds.close();
    }
}

==接收端代码:==

public class Url04 {
    public static void main(String[] args) throws IOException {
        //接收端
        DatagramSocket sd=new DatagramSocket(10000);
        //准备接受数据
        byte[] by=new byte[1024];
        //打包数据
        DatagramPacket dp=new DatagramPacket(by,0,by.length);
        //接受
        sd.receive(dp);//堵塞接受
        //处理数据
        int len=dp.getLength();
        System.out.println(new String(by,0,len));
        sd.close();

    }
}

效果图:

在这里插入图片描述


🍣**案例2:》》》》通过TCP协议实现客户端和服务端的数据交互**

  • TCP实现多用户登录的服务端
  • 通过多线程实现服务器端的多用户登录
  • 一个客户端就要开启一个 线程为当前客户端服务
  • 案例:客户端登录操作,假设密码和账户名都是123,多个用户进行登录

客户端的代码实现:》》》

//客户端
public class Url05 {
    public static void main(String[] args) throws IOException {
        System.out.println("------客户端开启-----");
        //定义客户端
        Socket client=new Socket("localhost",8787);
        boolean flag=true;
        while(flag){
        //获取输出流
        DataOutputStream output=new DataOutputStream(client.getOutputStream());
        //IO操作

            System.out.println("请输入用户名:");
            BufferedReader read=new BufferedReader(new InputStreamReader(System.in));
            String name= read.readLine();
            System.out.println("请输入密码:");
            String password=(new Scanner(System.in).next());
            output.writeUTF(name+"&"+password);

            //刷出
            output.flush();
            DataInputStream input=new DataInputStream(client.getInputStream());
            System.out.println(input.readUTF());
            //关闭
            input.close();
            output.close();
            read.close();
        }
        client.close();
    }
}

服务端的代码实现:》》》

//服务端
public class Url06 {
    public static void main(String[] args) throws IOException {
        System.out.println("-----服务器开启------");
        //定义服务器
        ServerSocket ss=new ServerSocket(8787);
        boolean flag=true;
        while(flag) {
            //阻塞接受
            Socket client = ss.accept();
            System.out.println("一个客户链接");
            //通过线程实现多个客户端访问
            new Thread(new Method(client)).start();
        }
            ss.close();
    }
}

//一个客户端访问的全部流程
class Method implements Runnable{
    private Socket client;//Socket类型的客户端对象
    private DataInputStream input;//字节功能输入流
    private DataOutputStream output;//字节功能输出流
    public Method(Socket client) throws IOException {
        //初始化
        this.client=client;
        //IO流数据的输入输出
        input = new DataInputStream(client.getInputStream());
        output = new DataOutputStream(client.getOutputStream());
    }

    //封装关闭方法
    public void close() throws IOException {
        //关闭
        input.close();
        output.close();
        client.close();
    }
   //重写方法
    @Override
    public void run() {
        //处理数据
        String[] str=null;
        try {
            str = input.readUTF().split("&");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 登录数据的判断
            if ("123".equals(str[0]) && "123".equals(str[1])) {
                try {
                    output.writeUTF("登录成功~");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    output.writeUTF("登录失败!");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }
}

结果:》》》

在这里插入图片描述


4、通过URL实现一个简单的爬虫
  • 直接上代码
public class Url02 {
    public static void main(String[] args) throws IOException {
        System.out.println("---接受中----");
        URL url=new URL("https://www.taobao.com");
        BufferedReader fr= new BufferedReader(new InputStreamReader(url.openStream()));
        String str;
        while((str=fr.readLine())!=null){
            System.out.println(str);
        }
        fr.close();
    }
}

结果:》》》

在这里插入图片描述


🥂🥂🥂🥂🥂🥂🥂·······完结········🥂🥂🥂🥂🥂🥂🥂·

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

每日小新

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值