网络编程--狂神

学习视频来自B站,感谢狂神的分享:B站视频地址

1.计算机网络

计算机网络
  指将地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路连接起来,在网络操作系统,网络管理软件及网络通信协议的管理和协调下,实现资源共享和信息传递的计算机系统。

类别架构
网络编程TCP/IP   CS
javaWeb网页编程   BS

实现网络通信的要素:

  • 双方通讯地址 :ip地址 + 端口号
  • 双方通讯协议
    osi与tcp/ip

2.ip

ip地址:inetAddress

  • 定位一台网络上的计算机
  • ip地址的分类:
    • ip地址分类(ipv4/ipv6)
      ipv4: 四个字节组成,如127.0.0.1,没给位置0~255,大约有42亿。30亿在北美,亚洲4亿。2011年已经用完
      ipv6: 128位, 8个无符号整数(16进制),如fe80::59f0:8233:348c:e377%12
    • 公网(互联网)与私网(局域网)
    • 公网分为ABCD四类地址
    • 私网 192.168.xx.xx 一般都是局域网
//InetAddress类:
try {
     //查询本机
     InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
     InetAddress inetAddress2 = InetAddress.getByName("localhost");
     InetAddress inetAddress3= InetAddress.getLocalHost();
     System.out.println(inetAddress1);   //输出: /127.0.0.1
     System.out.println(inetAddress2);   //输出: localhost/127.0.0.1
     System.out.println(inetAddress3);   //输出: DESKTOP-40LDP54/172.22.190.33
     //查询网站ip
     InetAddress inetAddress4= InetAddress.getByName("www.baidu.com");
     System.out.println(inetAddress4.getAddress());      //输出: [B@7f31245a
     System.out.println(inetAddress4.getCanonicalHostName());   //输出:220.181.38.149
     System.out.println(inetAddress4.getHostAddress());  //输出:220.181.38.149
     System.out.println(inetAddress4.getHostName());     //输出:www.baidu.com
 } catch (UnknownHostException e) {
     e.printStackTrace();
 }

3.端口

可以认为是设备与外界通讯交流的出口。
端口可分为虚拟端口和物理端口:虚拟端口指计算机内部或交换机路由器内的端口,不可见。例如计算机中的80端口、21端口、23端口等。物理端口又称为接口,是可见端口,计算机背板的RJ45网口,交换机路由器集线器等RJ45端口。

  • 不同的进程有不同的端口号,端口号不可冲突!用来区分软件
  • 一般被规定为0~65535。TCP, UDP 每个协议都有65535,所以总共有 65535 * 2个端口。在单个协议下端口号不能冲突
  • 端口分类
类别详细
公有端口范围: 0~1023
HTTP:80
HTTPS:443
FTP:21
Telent: 23
程序注册端口
分配给用户或者程序
范围:1014~49151
Tomcat:8080
MySQL:3306
Oracle:1521
动态、私有端口范围:49152~65535
开发程序,尽量不要用这个范围的端口

netstat -ano #查看所有端口
netstat -ano|findstr “5900” #查看指定端口
tasklist|findstr “8696” #查看指定端口的进程

public class TestInetSocketAddress {
    public static void main(String[] args) {
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1",8080);
        InetSocketAddress inetSocketAddress2 = new InetSocketAddress("localhost",8080);
        
        System.out.println(inetSocketAddress);  //  /127.0.0.1:8080
        System.out.println(inetSocketAddress2); //  localhost/127.0.0.1:8080

        System.out.println(inetSocketAddress.getAddress()); // /127.0.0.1
        System.out.println(inetSocketAddress.getHostName());// activate.navicat.com
        System.out.println(inetSocketAddress.getHostString());//activate.navicat.com
        System.out.println(inetSocketAddress.getPort());    //8080
    }
}

4.通讯协议

网络通信协议:一种网络通用语言,为连接不同操作系统和不同硬件体系结构的互联网络提供通信支持,是一种网络通用语言。

TCP/IP协议簇:实际上是一组协议

重要的协议:

  • TCP : 传输控制协议(Transmission Control Protocol)是一种面向连接的、可靠的、基于字节流的传输层通信协议。
    三次握手、四次挥手
  • UDP : 用户数据报协议(User Datagram Protocol)一个无连接的传输协议
  • IP:网络互连协议(Internet Protocol)是TCP/IP体系中的网络层协议。

tcp与udp对比:
tcp与udp对比

5.tcp实现通讯

// ----------------------客户端---------------------------
public class TcpClientOne {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream outputStream = null;
        try {
            // 1. 创建连接,指向服务器的地址和端口
            InetAddress ip = InetAddress.getByName("127.0.0.1");
            socket = new Socket(ip,9998);
            // 2. 发送IO流数据
            outputStream = socket.getOutputStream();
            outputStream.write("你好,我是客户端".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //3. 关闭io流与socket(先开后关,应先判断为空)
            try {
                if(outputStream != null){ outputStream.close();}
                if(socket != null){ socket.close();}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
// ----------------------服务端---------------------------
public class TcpServerOne {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream inputStream = null;
        ByteArrayOutputStream bos = null;
        try {
            //1.创建服务端,指定端口号
            serverSocket = new ServerSocket(9998);
            //2.等待客户端连接(阻塞式监听,一直等待客户端连接)
            accept = serverSocket.accept();	
            //3.获取输入流,打印信息
            inputStream = accept.getInputStream();
            bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1){
                bos.write(buffer,0,length);
            }
            //4.输出信息
            System.out.println(bos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭各种流,先开后关
            try {
                if(bos != null){ bos.close();}
                // .......省略另外几种流的关闭
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

6.tcp文件上传

// ----------------------客户端---------------------------
public class TcpClientTwo {
    public static void main(String[] args) {
        try {
            //1. 创建socket,指定服务端地址和端口
            Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9998);
//            new Socket(InetAddress.getByAddress("127.0.0.1".getBytes()),9998);
            //2. 获取输出流
            OutputStream outputStream = socket.getOutputStream();
            //3. 读取文件
            FileInputStream fis = new FileInputStream(new File("sun.jpg"));
            //4.传输文件
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) != -1){
                outputStream.write(buffer,0,length);
            }
            //5.传输完毕,通知服务端
            socket.shutdownOutput();
            //6.接收服务端信息,打印出来
            byte[] buffer2 = new byte[1024];
            InputStream inputStream = socket.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            if((length = inputStream.read(buffer2)) != -1){
                baos.write(buffer2,0,length);
            }
            System.out.println(baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // ...此处省略关闭流代码...
        }
    }
}
// ----------------------服务端---------------------------
public class TcpServerTwo {
    public static void main(String[] args) {
        try {
            //1.创建服务端,指定端口;获取socket
            ServerSocket serverSocket = new ServerSocket(9998);
            Socket accept = serverSocket.accept();
            //2.获取输入流
            InputStream inputStream = accept.getInputStream();
            //3.文件输出流
            FileOutputStream fos = new FileOutputStream(new File("sun2.jpg"));
            //4.开始输出
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1){
                fos.write(buffer,0,length);
            }
            //5.接收完毕,告诉客户端可以断开
            OutputStream outputStream = accept.getOutputStream();
            outputStream.write("服务端接收完毕,可以断开".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        	// ...此处省略关闭流代码...
        }
    }
}

7.udp发送消息

// ------------------udp数据发送端----------------------
public class UdpSendOne {
    public static void main(String[] args) {
        try {
            //1.建立一个socket
            DatagramSocket socket = new DatagramSocket();
            //2.确认ip、端口、发送信息
            String msg = "你好,发给你一条信息";
            InetAddress ip = InetAddress.getByName("127.0.0.1");
            int port = 9998;
            //3.创建发送包
            DatagramPacket packet = new DatagramPacket(msg.getBytes(),msg.getBytes().length,ip,port);
            //4.开始发送
            socket.send(packet);
            //5.关闭流
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
// ------------------udp数据接收端----------------------
public class UdpReceiveOne {
    public static void main(String[] args) {
        try {
            //1.开放端口
            DatagramSocket receiveSocket = new DatagramSocket(9998);
            //2.创建接收数据包
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
            //3.接收数据
            receiveSocket.receive(packet);  //阻塞接收,接到数据前不关闭
            //4.打印信息
            System.out.println(packet.getAddress());
            System.out.println(new String(packet.getData()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

8.udp消息循环发送

// ------------------udp数据发送端----------------------
public class UdpSendTwo {
    public static void main(String[] args) {
        try {
            //1.创建socket对象
            DatagramSocket socket = new DatagramSocket();
            //2.从控制台接收数据
            BufferedReader inputStream = new BufferedReader(new InputStreamReader(System.in));
            DatagramPacket packet = null;
            //循环发送
            while (true) {
                //3.创建数据发送包
                String msg = inputStream.readLine();
                byte[] bytes = msg.getBytes();
                packet = new DatagramPacket(bytes,bytes.length,
                        InetAddress.getByName("localhost"),9998);
                //4.开始发送
                socket.send(packet);
                if(msg.equals("bye")){ break; }
            }
            //5.关闭
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
// ------------------udp数据接收端----------------------
public class UdpReceiveTwo {
    public static void main(String[] args) {
        try {
            //1.开放端口
            DatagramSocket socket = new DatagramSocket(9998);
            while (true) {
                //2.创建数据接收包
                byte[] bytes = new byte[1024];
                DatagramPacket packet = new DatagramPacket(bytes,bytes.length);
                //3.接收数据(阻塞接收)
                socket.receive(packet);
                //4.输出数据
                String msg = new String(packet.getData());
                System.out.println(msg);
                if(msg.equals("bye")){ break; }
            }
            //5.关闭
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

9.udp双向聊天

// 创建两个Runnable接口实现类,一个发送数据,一个接收数据
//然后再用两个类,分别启动两个线程
// ----------------------- 发送线程 -----------------------
public class UdpSendThree implements Runnable {
    //1.创建socket对象
    DatagramSocket socket;
    //2.从控制台接收数据
    BufferedReader inputStream = new BufferedReader(new InputStreamReader(System.in));
    DatagramPacket packet = null;
    //创建构造方法
    private String toIp;
    private int toPort;
    public UdpSendThree(String toIp, int toPort) { this.toIp = toIp; this.toPort = toPort; }

    @Override
    public void run() {
        try {
            socket = new DatagramSocket();
            //循环发送
            while (true) {
                //3.创建数据发送包
                String msg = inputStream.readLine();
                byte[] bytes = msg.getBytes();
                packet = new DatagramPacket(bytes,bytes.length,InetAddress.getByName(toIp),toPort);
                //4.开始发送
                socket.send(packet);
                if(msg.equals("bye")){ break; }
            }
            //5.关闭
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
// ----------------------- 接收线程 -----------------------
public class UdpReceiveThree implements Runnable {
    DatagramSocket socket = null;
    DatagramPacket packet = null;
    private int receivePort;
    public UdpReceiveThree(int receivePort) {
        this.receivePort = receivePort;
    }

    @Override
    public void run() {
        try {
            //1.开放端口
            socket = new DatagramSocket(this.receivePort);
            while (true) {
                //2.创建数据接收包
                byte[] bytes = new byte[1024];
                packet = new DatagramPacket(bytes,bytes.length);
                //3.接收数据(阻塞接收)
                socket.receive(packet);
                //4.输出数据
                String msg = new String(packet.getData());
                System.out.println(msg);
                if(msg.equals("bye")){ break; }
            }
            //5.关闭
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

用两个类分别启动

10.URL

在WWW上,每一信息资源都有统一的且在网上唯一的地址,该地址就叫URL(Uniform Resource Locator,统一资源定位器),它是WWW的统一资源定位标志,就是指网络地址。

  • URL由三部分组成:资源类型、存放资源的主机域名、资源文件名。
  • 也可认为由4部分组成:协议、主机、端口、路径
URL url = new URL("http://localhost:8080/index?name=bilibili");
System.out.println(url.getProtocol());  //  http
System.out.println(url.getHost());      //  localhost
System.out.println(url.getPath());      //  /index
System.out.println(url.getPort());      //  8080
System.out.println(url.getQuery());     //  name=bilibili
// 使用url下载资源。注意while中的写法
public static void main(String[] args) {
    try {
        //1.建立下载地址
        URL url = new URL("https://pics2.baidu.com/feed/0eb30f2442a7d933b9612a1bc0ecc11472f0013f.jpeg");
        //2.链接到这个地址
        HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
        //3.输入流
        InputStream inputStream = httpURLConnection.getInputStream();
        //4.文件输出流
        FileOutputStream fos = new FileOutputStream("girl.jpeg");
        //5.下载输出
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer) ) != -1){
            fos.write(buffer,0,length);     //注:此处写成fos.write(buffer),可能出现文件错乱
        }
        //6.断开
        fos.close();
        inputStream.close();
        httpURLConnection.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值