shanX
文章31
标签17
分类9
JAVA-网络编程

JAVA-网络编程

网络编程

概述

类似于平信信件

其中涉及计算机网络基本概念,网络编程的目的就是传播交流信息、数据交换、通信;达到的效果是需要如何准确定位到网络上的一台主机(IP、端口、资源),对主机进行数据传输

与 JAVAWEB 网页编程的 B/S 架构不同,网络编程是 C/S 编程。

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

网络编程的目的:

交流信息,数据交换,通信。

想要达到这个效果需要什么

  1. 如何准确地定位网络上的一台主机,192.168.0.176:3553 IP : 端口,定位到这个计算机上的某个资源。
  2. 找到了这个主机,如何传输数据?
  3. javaweb : 网页编程 B/S 网络编程 :TCP/IP 、C/S

网络通信的要素

如何实现网络的通信?

  1. 通信双方的 ip端口号
  2. 规则:TCP/IP 、OSI

小结:

  1. 网络编程中两个主要的问题
    • 如何准确定位到网络上一台或多台主机
    • 找到主机之后如何进行通信
  2. 网络编程中的要素
    • IP 和端口号
    • 网络通信协议 UDP TCP/IP
  3. 万物皆对象

IP

ip 地址:InetAddress

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

  • 127.0.0.1 本机 localhost

  • ip 地址的分类

    • ipv4 / ipv6

      • IPV4 127.0.0.1 四个字节组成 42 亿 2011 年已被用尽

      • IPV6 128 位、8 个无符号整数组成 abcde

        2834:4bba:aacb:0013:1241:1aaa:1341:6254

    • 公网 (互联网)- 私网(局域网)

      • ABCD 类地址
  • 域名:记忆 IP 问题

获取相关信息

public class TestInterAddress {
    public static void main(String[] args) {
        try {
            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);

            InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8080);
            System.out.println(inetSocketAddress);

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

            System.out.println( inetAddress4.getCanonicalHostName());
            System.out.println( inetAddress4.getHostAddress());
            System.out.println( inetAddress4.getHostName());
            System.out.println( inetAddress4.getClass());


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

端口

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

  • 不同的进程有不同的端口号,用来区分软件。

  • 被规定范围 0 - 65535

  • TCP,UDP :65535*2 TCP 用 80 UDP 也可以用 80 单个协议下,端口号不能冲突

  • 端口分类

    • 公有端口 0-1023 系统进程使用,尽量不用
      • HTTP : 80
      • HTTPS : 443
      • FTP : 21
      • Telent : 23
    • 程序注册端口,1024-49151,分配用户或者程序
      • Tomcat : 8080
      • MySql : 3306
      • Oracle :1521
      • postgre : 5432
    • 动态,私有:49152 - 65535
    netstat -ano 查看所有端口
    
    netstat -ano|findstr "5900"   查看指定端口
    
    tasklist|findstr "8696"  查看指定端口的进程
    
    任务管理器  ctrl + shift + esc
    

通信协议

协议:约定,就好比我们现在说的是普通话;

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

问题:非常的复杂?

大事化小:分层;

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

重要:

  • TCP::用户传输协议;

  • UDP:用户数据报协议;

  • IP:网络互连协议;

TCP / UDP 对比

  • TCP: 连接稳定、三次握手四次挥手、客户端与服务端、传输需要释放效率低;
  • UDP: 不连接不稳定、客户端服务端无明确界限、无需准备、 DDOS 洪泛攻击;

TCP

客户端

  1. 连接服务器 Socket;
  2. 发送消息;
//客户端
public class TcpClientDemo1 {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        try {
            //要知道服务器的地址
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            int port = 9999;
            //创建一个socket连接
            socket = new Socket(serverIP, port);
            //发送消息
            os = socket.getOutputStream();
            os.write("message!".getBytes());
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

服务器

  1. 建立服务的端口 ServerSocket;
  2. 等待用户的链接 accept;
  3. 接收用户的消息;
//服务端
public class TcpServerDemo1 {
    public static void main(String[] args) throws Exception {

        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream bs = null;
        try {
            //有一个服务器地址
             serverSocket = new ServerSocket(9999);
            //等待客户端连接
            socket = serverSocket.accept();
            //读取客户端的信息
            is = socket.getInputStream();
            //管道流
            bs = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                bs.write(buffer, 0, len);
            }
            System.out.println(bs.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bs != null) {
                try {
                    bs.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}

TCP 文件上传

客户端

//客户端提交文件
public class TcpClientDemo2 {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        FileInputStream fis = null;
        try {
            //创建一个socket连接
            socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
            //创建一个输出流
            os = socket.getOutputStream();
            //读取文件
            fis = new FileInputStream(new File("D:\\workspace\\IDEA-workspace\\kuangshen_java\\网络编程\\src\\com\\inte\\tcp\\bg17.jpg"));
            //写出文件
            byte[] buffer = new byte[1024];
            int len;
            while ((len=fis.read(buffer))!=-1) {
                os.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if (fis!=null) {
                try {
                    fis.close();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (os!=null) {
                try {
                    os.close();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null) {
                try {
                    socket.close();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

服务端

//服务端接收文件
public class TcpServerDemo2 {
    public static void main(String[] args) {
        //创建服务
        ServerSocket serverSocket = null;
        //监听客户端的连接
        Socket socket = null;
        //获取输入流
        InputStream is = null;
        //文件输出
        FileOutputStream fos = null;

        try {
            serverSocket = new ServerSocket(9000);
            socket = serverSocket.accept(); //阻塞式监听,会一直等待客户端连接
            is = socket.getInputStream();
            fos = new FileOutputStream(new File("D:\\workspace\\IDEA-workspace\\kuangshen_java\\网络编程\\src\\com\\inte\\tcp\\" + Math.random()*1000000000 + ".jpg"));
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len=is.read(buffer))!=-1){
                fos.write(buffer, 0, len);
                System.out.println("接收文件.....");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if (fos!=null) {
                try {
                    fos.close();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (is!=null) {
                try {
                    is.close();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null) {
                try {
                    socket.close();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket!=null) {
                try {
                    serverSocket.close();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Tomcat

服务端

  • 自定义 S
  • Tomcat 服务器 S : JAVA 后台开发

客户端

  • 自定义 C
  • 浏览器 B

UDP

Client1

public static void main(String[] args) throws Exception {
        //建立一个socket
        DatagramSocket socket = new DatagramSocket();

        //建个包
        String msg = "hello my friend!!";

        //发送给谁
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9090;

        //数据,数据的长度起始,要发送给谁;
        DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);

        //发送包
        socket.send(datagramPacket);

    }

Client2

public static void main(String[] args) throws Exception {
        //开放端口
        DatagramSocket socket = new DatagramSocket(9090);

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

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

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

        socket.close();
    }

案例:UDP 实现聊天

//发送方
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();
    }
//接收方
 public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(6666);

        while(true){
            // prepare receive the packet
            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.print(receiveData);
            if (receiveData.equals("bye")) break;
        }
        socket.close();
    }

多线程:实现同时收发

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

public class TalkReceive implements Runnable {
    DatagramSocket socket = null;
    private int port;
    private String msgFrom;
    public TalkReceive(int port, String msgFrom){
        this.port = port;
        this.msgFrom = msgFrom;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        try {
            while(true){
                // prepare receive the packet
                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();
    }
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class TalkSend implements Runnable {
    DatagramSocket socket = null;
    BufferedReader reader = null;
    private int fromPort;
    private String toIP;
    private int toPort;

    public TalkSend(int fromPort, String toIP, int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;
        try{
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            String data = null;
            try {
                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 (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
public class TalkStu {
    public static void main(String[] args) {
        // 开启两个线程
        new Thread(new TalkSend(7878, "localhost", 9988)).start();
        new Thread(new TalkReceive(8899, "teac")).start();
    }
}
public class TalkTeac {
    public static void main(String[] args) {
        new Thread(new TalkSend(5555, "localhost", 8899)).start();
        new Thread(new TalkReceive(9988, "Stu")).start();
    }
}

URL

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

DNS 域名解析 : 协议:// ip 地址:端口/ 项目名 / 资源

下载网络资源:

public class UrlDownload {
    public static void main(String[] args) throws Exception {
        // 1. download Address
        URL url = new URL("url"); // 网络资源地址
        // 2. connect HTTP
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream fos = new FileOutputStream("fileName.txt"); // 下来的命名

        byte[] buffer = new byte[1024];
        int len;
        while((len = inputStream.read(buffer)) != -1){
            fos.write(buffer, 0, len); // 写出数据
        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect(); // 断开连接
    }
}
本文作者:shanX
本文链接:https://rhymexmove.github.io/2021/04/12/6b4cf36b2046/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可