zoukankan      html  css  js  c++  java
  • 网络编程

    Java网络编程

    一.网络通信的要素

    • 通信双方的地址:
      • ip地址
      • 端口号
    • 网络通信协议

    IP

    ip地址对应java的类:InetAddress

    • 唯一定位一台网络上计算机
    • 127.0.0.1 本机地址localhost
    • IP地址的分类:
      • ipv4 127.0.0.1.四个字节(32位)组成,42亿
      • ipv6 16个字节(128位)组成
    • 公网(互联网)-私网(局域网)
    • 域名:记忆IP问题
    package test;
    import java.net.InetAddress;
    public class file {
        public static void main(String[] args) throws Exception{
            //查询网站ip地址
             InetAddress inetAddress1=InetAddress.getByName("www.baidu.com");
             //查询本机ip地址
             InetAddress inetAddress2=InetAddress.getByName("localhost");
             InetAddress inetAddress3=InetAddress.getLocalHost();
            System.out.println(inetAddress1);
            System.out.println(inetAddress2);
            System.out.println(inetAddress3);
            //常用方法
            System.out.println(inetAddress1.getAddress());
            System.out.println(inetAddress1.getCanonicalHostName());//规范的名字,ip
            System.out.println(inetAddress1.getHostAddress());//ip
            System.out.println(inetAddress1.getHostName());//域名
         }
    }
    

    端口

    端口表示计算机上的一个程序的进程:

    • 不同的进程有不同的端口号
    • 规定为0-65535
    • 分为TCP和UDP端口(65535*2);单个协议下端口号不能冲突

    端口分类

    • 公有端口:0~1023
      • HTTP:80
      • HTTPS: 443
      • FTP:21
      • Telent:23
    • 程序注册端口:1024~49151,分配用户或者程序
      • Tomcat: 8080
      • MySQL: 3306
      • Oracle: 1521
    • 动态,私有:49152~65535

    netstart -ano查看所有端口
    netstart -ano|findstr "5900"查看指定的端口
    tasklist|findstr "8696"查看指定端口的进程

    package test;
    import java.net.InetSocketAddress;
    public class file {
        public static void main(String[] args) throws Exception{
            InetSocketAddress inetSocketAddress=new InetSocketAddress("127.0.0.1",8000);
            System.out.println(inetSocketAddress);
            //获取主机名
            System.out.println(inetSocketAddress.getAddress());
            System.out.println(inetSocketAddress.getHostName());
            System.out.println(inetSocketAddress.getHostString());
            //获取端口号
            System.out.println(inetSocketAddress.getPort());
         }
    }
    

    通信协议

    TCP/IP协议簇

    TCP:用户传输协议
    UDP:用户数据报协议
    IP:网络互连协议
    TCP vs UDP
    TCP:打电话

    • 连接,稳定
    • 三次握手四次挥手
      • 最少需要3次,保证稳定连接
    • 客户端,服务端
    • 传输完成,释放连接,效率低
      UDP:发消息
    • 不连接,不稳定
    • 客户端,服务端:没有明确的界限
    • DDOS(饱和攻击)

    TCP

    客户端

    1. 链接服务器Socket
    2. 发送消息
    package oop;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    public class Client {
        public static void main(String[] args) throws Exception{
            Socket socket=null;
            OutputStream os=null;
            try{
                //1.要知道服务器地址,端口号
                InetAddress serverIp = InetAddress.getByName("127.0.0.1");
                int port = 9999;
                //2.创建一个socket连接
                socket=new Socket(serverIp,port);
                //发送消息
                os=socket.getOutputStream();
                os.write("你好".getBytes());
    
        }catch(
        UnknownHostException e)
    
        {
            e.printStackTrace();
    
        }finally{
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    }
    }
    

    服务端

    1. 建立服务的端口ServerSocket
    2. 等待用户的连接accept
    3. 接收用户的消息
    package oop;
    
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class Server {
        public static void main(String[] args) {
            ServerSocket serverSocket = null;
            Socket socket = null;
            ByteArrayOutputStream baos = null;
            InputStream ins = null;
            try {
                //要有一个地址
                serverSocket = new ServerSocket(9999);
                //等待客户端连接
                socket = serverSocket.accept();
                //读取客户端消息
                ins = socket.getInputStream();
                //管道流
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = ins.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                System.out.println(baos.toString());
    
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (baos != null) {
                    try {
                        baos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (ins != null) {
                    try {
                        ins.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (serverSocket != null) {
                    try {
                        serverSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
            }
    
        }
    }
    

    UDP

    发送消息

    • 发送端
    package oop;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    
    public class Client {
        public static void main(String[] args) throws Exception {
            //1.建立一个Socket
            DatagramSocket datagramSocket=new DatagramSocket();
            //2.建个包
            String msg="hello world";
            InetAddress localhost=InetAddress.getByName("127.0.0.1");
            int port=9000;
            DatagramPacket datagramPacket= new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);
            //3.发送包
            datagramSocket.send(datagramPacket);
            //关闭流
            datagramSocket.close();
    
        }
    }
    
    
    • 接收端
    package oop;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    public class Server {
        public static void main(String[] args) throws Exception {
            //开放端口
            DatagramSocket datagramSocket=new DatagramSocket(9000);
            //接收数据包
            byte[] buffer=new byte[1024];
            DatagramPacket datagramPacket=new DatagramPacket(buffer,0,buffer.length);
            datagramSocket.receive(datagramPacket);
            //关闭
            datagramSocket.close();
            System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
    
        }
    }
    

    二.URL

    统一资源定位符:定位互联网上的某一个资源
    格式:协议://ip地址:端口好//项目名//资源
    连接URL,下载资源

    package oop;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    public class Test2 {
        public static void main(String[] args) throws Exception {
            URL url=new URL("https://www.bilibili.com/video/BV1LJ411z7vY?p=12");
            //获取协议
            System.out.println(url.getProtocol());
            //获取主机
            System.out.println(url.getHost());
            //获取文件
            System.out.println(url.getPath());
            //获取文件全路径
            System.out.println(url.getFile());
            //获取参数
            System.out.println(url.getQuery());
            HttpURLConnection httpURLConnection=(HttpURLConnection) new url.openConnection();
            InputStream inputStream=httpURLConnection.getInputStream();
            FileOutputStream fos=new FileOutputStream("f.mp4");
            byte[] buffer=new byte[1024];
            int len;
            while((len=inputStream.read(buffer))!=-1){
                fos.write(buffer,0,len);
            }
            fos.close();
            inputStream.close();
            httpURLConnection.disconnect();
    
        }
    }
    
  • 相关阅读:
    C#开发: 通信篇-串口调试助手
    C#开发: 准备工作-C# 新建工程
    C#开发: 准备工作-Visual Studio 安装
    ESP8266 SDK开发: 外设篇-串口
    ESP8266 SDK开发: 外设篇-定时器,延时
    ESP8266 SDK开发: 外设篇-GPIO中断检测
    【java编程】加载Resources配置文件的方法
    【java高级编程】jdk自带事件模型编程接口
    【mybatis源码学习】mybtias知识点
    【java编程-Javassist】秒懂Java动态编程(Javassist研究)
  • 原文地址:https://www.cnblogs.com/python-road/p/13220867.html
Copyright © 2011-2022 走看看