05网络编程

网络编程

1.1 概述

什么是计算机网络

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

网络编程目的

传播交流信息,数据交换,通信

达到什么效果

tcp/ip c/s Client Server

javaweb b/s Browser Server

1.2 网络通信要素

如何实现网络通信?

通信双方地址:

  • ip
  • 端口号
  • 192.168.xx

规则:网络通信的协议

TCP/IP参考模型:
TCP/IP参考模型

小结

1,网络编程中的两个主要问题

  • 如何准确的定位到网络上的一台或者多台主机(ping命令)
  • 找到主机之后如何通信

2,网络编程中的要素

  • IP和端口号 IP
  • 网络通信协议 UDP ,TCP

3,万物皆对象

1.3 ip

ip地址:InetAddress

  • 唯一定位一台网络上的计算机

  • 127.0.0.1:本机localhost

  • ip地址分类

    • ipv4/ipv6

      • ipv4 127.0.0.1 4个字节组成
      • ipv6 fe80::aea:9086:b94:c926%12
    • 公网(互联网)-私网(局域网)

      • ABCD类地址
      • 192.168.xx.xx
  • 域名

    • ip
package test;

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

/**
 * ClassName: Test01
 * 测试IP--InetAddress
 * @Author syy
 * @Create 2023/5/15 20:20
 * @Version 10
 */
public class Test01 {
    public static void main(String[] args) {
        try {
            //查看本机IP地址
            InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
            System.out.println(inetAddress1);
            InetAddress inetAddress2 = InetAddress.getByName("localhost");
            System.out.println(inetAddress2);
            InetAddress inetAddress3 = InetAddress.getLocalHost();
            System.out.println(inetAddress3);

            //查看网站IP地址
            InetAddress inetAddress4 = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress4);

            //常用方法
            System.out.println(inetAddress4.getCanonicalHostName()); //规范的名字
            System.out.println(inetAddress4.getHostAddress()); //ip
            System.out.println(inetAddress4.getHostName()); //域名 或者自己电脑的名字

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

1.4 端口

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

  • 不同的进程有不同的端口号

  • 规定端口号范围:0-65535

  • TCP/UDP : 单个协议下,端口号不能冲突

  • 端口分类

    • 共有端口:0–1023

      • HTTP端口号为 :80
      • HTTPS端口号为 :443
      • FTP端口号为 :21
      • telent端口号为 :23
    • 注册端口:1024–49151,分配给用户使用

      • Tomcat: 8080
      • MySQL: 3306
      • Oracle: 1521
    • 动态,私有: 49152–65535

      netstat -ano #查看所有窗口
      netstat -ano|findstr "xxxx" #查看指定的端口
      tasklist|findstr "8932" #查看指定端口的进程
      

      端口
      查看指定端口协议

1.5 通信协议

协议:约定

**网络通信协议:**速率,传输码率,代码结构…

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

要点:

  • TCP:用户传输协议
  • UDP:用户数据报协议

重要的协议

  • TCP
  • IP:网络互联协议

TCP UDP对比

TCP:打电话

  • 连接 稳定
  • “三次握手” “四次挥手”

三次握手
四次挥手

  • 客户端 服务端
  • 传输完成,释放连接,效率较低

UDP:发短信

  • 不连接 不稳定
  • 客户端 服务端:没有明确的界限
  • 不管有没准备好,直接发送
  • DDOS:洪水攻击(饱和攻击):一直发送,导致端口堵塞

1.6 TCP

客户端

  1. 连接服务器

  2. 发送消息

    package test;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.InetAddress;
    import java.net.Socket;
    
    
    /**
     * ClassName: TestServer02
     * 客户端
     * @Author syy
     * @Create 2023/5/15 22:03
     * @Version 10
     */
    
    //客户端
    public class TestTCPClient01 {
        public static void main(String[] args) {
            Socket socket = null;
            OutputStream os = null;
            try {
                //1.要知道服务器的地址 端口号
                InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
                int port = 9999;
                //2.创建一个socket连接
                socket = new Socket(inetAddress, port);
                //3.发送消息io流
                os = socket.getOutputStream();
                os.write("一起学习网络编程吧!".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (os != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    

服务端

  • 建立服务端端口 ServerSocket

  • 等待用户的链接 accept

  • 接收用户消息

    package test;
    
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    /**
     * ClassName: TestTCPClient01
     * 服务端
     * @Author syy
     * @Create 2023/5/15 22:02
     * @Version 10
     */
    
    public class TestServer01 {
        public static void main(String[] args) {
            ServerSocket serverSocket = null;
            Socket socket = null;
            InputStream is = null;
            ByteArrayOutputStream baos = null;
            try {
                //1.初始化服务端socket并且绑定9898端口
                serverSocket = new ServerSocket(9999);
                while (true) {
                    //2.等待客户端连接
                    socket = serverSocket.accept();
    
                    //3.读取客户端的获取输入流
                    is = socket.getInputStream();
    
                    //管道流
                    baos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = is.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 (is != null) {
                    try {
                        is.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();
                    }
                }
            }
        }
    }
    
    
文件上传

服务端

package test;

import javax.swing.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * ClassName: TestServer02
 *
 * @Author syy
 * @Create 2023/5/16 11:21
 * @Version 10
 */
public class TestServer02 {
    public static void main(String[] args) throws Exception {
        //1.创建服务
        ServerSocket serverSocket = new ServerSocket(9000);

        //2.监听客户端连接
        Socket socket = serverSocket.accept(); //阻塞式监听

        //3.获取输入流
        InputStream inputStream = socket.getInputStream();
        //4.文件输出
        FileOutputStream fileOutputStream = new FileOutputStream(new File("receive.png"));
        byte[] buffer  = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1){
           fileOutputStream.write(buffer,0,len);
        }

        //通知客户端接收完毕
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("I have completed the transmission,please disconnect!".getBytes());

        //5.关闭资源
        fileOutputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
    }
}

客户端

package test;

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

/**
 * ClassName: TestTCPClient02
 *
 * @Author syy
 * @Create 2023/5/16 10:57
 * @Version 10
 */
public class TestTCPClient02 {
    public static void main(String[] args) throws Exception {
        //1.创建一个socket连接
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);

        //2.创建一个输出流
        OutputStream outputStream = socket.getOutputStream();

        //3.读取文件
        FileInputStream fileInputStream = new FileInputStream(new File("view.png"));
        //4.写出文件
        byte[] buffer  = new byte[100];
        int len;
        while ((len = fileInputStream.read(buffer)) != -1){
            outputStream.write(buffer,0,len);
        }

        //通知服务器,已经结束
        socket.shutdownOutput(); //已经传输完成

        //确认服务器接收完毕,之后断开连接
        InputStream inputStream = socket.getInputStream();
        //String byte[]
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        byte[] buffer2 = new byte[1024];
        int len2;
        while ((len2 = inputStream.read(buffer2)) != -1){
            byteArrayOutputStream.write(buffer2,0,len2);
        }

        System.out.println(byteArrayOutputStream);

        //5.关闭资源
        byteArrayOutputStream.close();
        inputStream.close();
        fileInputStream.close();
        outputStream.close();
        socket.close();
    }
}

Tomcat

服务端

  • 自定义
  • Tomcat服务器

客户端

  • 自定义
  • 浏览器

1.7 UDP

没有真正的客户端和服务器端端口的概念

发送消息

package test;

import java.lang.reflect.ParameterizedType;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * ClassName: TestUDPClient01
 * UDP不需要连接服务器
 * @Author syy
 * @Create 2023/5/16 13:49
 * @Version 10
 */
public class TestUDPClient01 {
    public static void main(String[] args) throws Exception {
        //1.建立一个socket连接
        DatagramSocket socket = new DatagramSocket();

        //2.建包
        String msg = "需要连接服务器!";
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9898;

        //3.数据 数据的长度 要发送的对象
        DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);

        //4.发送包
        socket.send(packet);

        //5.关闭流
        socket.close();
    }
}

接收端

package test;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.PasswordAuthentication;
import java.net.SocketException;

/**
 * ClassName: TestUDPServer01
 * 服务器
 * @Author syy
 * @Create 2023/5/16 13:56
 * @Version 10
 */
public class TestUDPServer01 {
    public static void main(String[] args) throws Exception {
        //1.开放端口
        DatagramSocket socket = new DatagramSocket(9898);

        //2.接收数据包
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);

        socket.receive(packet); //阻塞接收

        System.out.println(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData(),0,packet.getLength()));

        //3.关闭连接
        socket.close();
    }
}

UDP聊天实现

发送消息

package chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * ClassName: TestUDPSender01
 *
 * @Author syy
 * @Create 2023/5/16 14:39
 * @Version 10
 */
public class TestUDPSender01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(8888);

        //准备数据:控制台读取 System.in
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while (true){
            String data = reader.readLine();
            byte[] datas = data.getBytes();
            DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 6666));

            socket.send(packet);

            if (data.equals("bye")){
                break;
            }
        }
        socket.close();
    }

}

接收消息

package chat;

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

/**
 * ClassName: TestUDPReceive01
 *
 * @Author syy
 * @Create 2023/5/16 14:59
 * @Version 10
 */
public class TestUDPReceive01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(6666);
        while (true){

            //准备接收包裹
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container, 0, container.length);
            socket.receive(packet); //阻塞式接收

            //断开连接 bye
            byte[] data = packet.getData();
            String receiveData = new String(data, 0, data.length);

            System.out.println(receiveData);

            if (receiveData.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

实现双方互相聊天(student teacher)

发送端

package chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * ClassName: TestTalkSend
 * 实现聊天
 * @Author syy
 * @Create 2023/5/16 15:47
 * @Version 10
 */
public class TestTalkSend implements Runnable {
    DatagramSocket socket = null;
    BufferedReader reader = null;

    private int fromPort;
    private String toIP;
    private int toPort;

    public TestTalkSend(int fromPort, String toIP,int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;

        try {
            socket = new DatagramSocket(fromPort);
            //准备数据:控制台读取 System.in
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public TestTalkSend() {
    }


    @Override
    public void run() {
        while (true) {
            try {
                String data = reader.readLine();
                byte[] datas = data.getBytes();
                DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIP, this.toPort));

                socket.send(packet);

                if (data.equals("bye")) {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            socket.close();
        }
    }
}

接收端

package chat;

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

/**
 * ClassName: TestTalkReceive
 *
 * @Author syy
 * @Create 2023/5/16 17:05
 * @Version 10
 */
public class TestTalkReceive implements Runnable{
    DatagramSocket socket = null;
    private int port;
    private String msgFrom;

    public TestTalkReceive(int port,String msgFrom) {
        this.port = port;
        this.msgFrom = msgFrom;
        try {
            socket = new DatagramSocket(6666);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){

            try {
                //准备接收包裹
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                socket.receive(packet); //阻塞式接收

                //断开连接 bye
                byte[] data = packet.getData();
                String receiveData = new String(data, 0, data.length);

                System.out.println(msgFrom+": "+receiveData);

                if (receiveData.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}

学生

package chat;

/**
 * ClassName: TestTalkStudent
 * 学生
 * @Author syy
 * @Create 2023/5/16 17:41
 * @Version 10
 */
public class TestTalkStudent {
    public static void main(String[] args) {
        //开启两个线程
       new Thread(new TestTalkSend(7777,"localhost",5656)).start();
        new Thread(new TestTalkReceive(8989,"Teacher")).start();
    }
}

老师

package chat;

/**
 * ClassName: TestTalkTeacher
 * 老师
 * @Author syy
 * @Create 2023/5/16 17:48
 * @Version 10
 */
public class TestTalkTeacher {
    public static void main(String[] args) {
        new Thread(new TestTalkSend(5555,"localhost",8989)).start();
        new Thread(new TestTalkReceive(5656,"student")).start();
    }

}

1.8 URL

统一资源定位符:定位资源,定位互联网上的某一个资源

DNS域名解析:www.baidu.com xxx.x…x…x

协议://ip地址:端口/项目名/资源1
package chat;

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

/**
 * ClassName: TestURL
 *
 * @Author syy
 * @Create 2023/5/16 19:28
 * @Version 10
 */
public class TestURL {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://localhost:8080/helloworld/index.jsp?username = yuer&password = 123");
        System.out.println(url.getProtocol());  //协议
        System.out.println(url.getHost());  //主机ip
        System.out.println(url.getPort());  //端口
        System.out.println(url.getPath());  //文件
        System.out.println(url.getFile());  //全路径
        System.out.println(url.getQuery());  //参数

    }
}

运行结果:

http
localhost
8080
/helloworld/index.jsp
/helloworld/index.jsp?username = yuer&password = 123
username = yuer&password = 123

通过URL下载网络上的资源

package chat;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * ClassName: TestURLDown
 * 通过URL下载网络上的资源
 * @Author syy
 * @Create 2023/5/16 19:57
 * @Version 10
 */
public class TestURLDown {
    public static void main(String[] args) throws IOException {
        //1. 下载地址
        URL url = new URL("https://m701.music.126.net/20230516203810/44cfc175352f8a4ffd9f5c70e4cfac67/jdyyaac/540e/5558/045c/cd30e6f86cb227a0011f364ab4e23f71.m4a");

        //2.连接到资源 http
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream fileOutputStream = new FileOutputStream("f71.m4a");
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1){
            fileOutputStream.write(buffer,0,len); //写出参数
        }
        fileOutputStream.close();
        inputStream.close();
        urlConnection.disconnect();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

septnancye

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

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

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

打赏作者

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

抵扣说明:

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

余额充值