• 网络编程


    入门

    c/s:Client/Server结构,客户端和服务器
    B/S:Browser/Server结构,浏览器和服务器

    java.net包中提供了两种常见的网络协议的支持:

    • UDP:用户数据报协议。无连接,数据限制在64kb以内
    • TCP:传输控制协议。有连接,三次握手

    网络编程三要素

    • 协议
    • IP
    • 端口

    狂神说

    计算机网络

    网络编程的目的:传播、交流信息

    IP、端口、通信协议

    IP

    InetAddress

    public class App {
        public static void main(String[] args) {
            try {
                InetAddress address = InetAddress.getByName("127.0.0.1");
                System.out.println(address);
                InetAddress address2 = InetAddress.getByName("localhost");
                System.out.println(address2);
                InetAddress address3 = InetAddress.getLocalHost();
                System.out.println(address3);
                InetAddress address4 = InetAddress.getByName("www.baidu.com");
                System.out.println(address4);
    
                //常用方法
                System.out.println(address4.getAddress());
                System.out.println(address4.getCanonicalHostName());//规范的名字
                System.out.println(address4.getHostAddress());//ip
                System.out.println(address4.getHostName());//域名,或者自己电脑的名字
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
    }
    

    端口

    一个端口对应一个程序的进程

    • 范围0-65535
    • TCP和UDP各有0-65535
    • 端口分类
      • 共有端口0-1023
        • HTTP:80
        • HTTS:443
        • FTP:21
        • Telent:23
      • 程序注册端口:1024-49151,分配用户或者程序
        • Tomcat:8080
        • mysql:3306
        • Oracle:1521
      • 动态、私有:49152-65535
    netstat -ano #查看所有的端口
    netstat -ano|findstr "5900" #查看指定的端口
    tasklist|findstr "8696" #查看指定端口的进程
    
    public class PortDemo {
        public static void main(String[] args) {
            InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 8080);
            InetSocketAddress socketAddress2 = new InetSocketAddress("localhost", 8080);
            System.out.println(socketAddress);
            System.out.println(socketAddress2);
    
            System.out.println(socketAddress.getAddress());
            System.out.println(socketAddress.getHostName());
            System.out.println(socketAddress.getPort());
        }
    }
    

    通信协议

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

    重要:

    • TCP:用户传输协议——打电话
      • 连接、稳定
      • 三次握手、四次挥手
      • 客户端、服务端
      • 传输完成、释放连接、效率低
    • UDP:用户数据协议——发短信
      • 不连接、不稳定
      • 客户端、服务器没有明确的界限
      • 不管有没有准备好,都可以发给你
      • DDOS:洪水攻击

    TCP实现聊天

    服务器

    1. 建立服务的端口 ServerSocket
    2. 等待用户的连接 Socket.accept()
    3. 接收客户端消息

    客户端

    1. 连接服务器Socket
    2. 发送消息
    //服务端
    public class ServerDemo1 {
        public static void main(String[] args) {
            ServerSocket serverSocket = null;
            Socket socket = null;
            InputStream inputStream = null;
            ByteArrayOutputStream baos = null;
            try {
                //1、一个地址
                serverSocket = new ServerSocket(9999);
                //2、等待客户端连接过来
                socket = serverSocket.accept();
                //3、读取客户端消息
                inputStream = socket.getInputStream();
                //管道流
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while((len=inputStream.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(inputStream!=null){
                    try {
                        inputStream.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();
                    }
                }
            }
        }
    }
    
    //客户端
    public class ClientDemo1 {
        public static void main(String[] args) {
            Socket socket = null;
            OutputStream outputStream = null;
            try {
                //1、知道服务器的地址,端口号
                InetAddress serverIP = InetAddress.getByName("127.0.0.1");
                int port = 9999;
                //2、创建一个socket连接
                socket = new Socket(serverIP,port);
                //3、发送消息,io流
                outputStream = socket.getOutputStream();
                outputStream.write("你好,欢迎来到未来世界".getBytes());
           } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if(outputStream!=null){
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(socket!=null){
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    

    TCP文件上传

    //客户端
    public class ClientDemo2 {
        public static void main(String[] args) throws IOException {
            //1、创建一个Socket连接
            Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9999);
            //2、创建一个输出流
            OutputStream os = socket.getOutputStream();
            //3、读取文件
            FileInputStream fileInputStream = new FileInputStream(new File("F:\1.png"));
            //4、写出文件
            byte[] buffer = new byte[1024];
            int len;
            while((len=fileInputStream.read(buffer))!=-1){
                os.write(buffer,0,len);
            }
            //通知服务器,我已经结束了
            socket.shutdownOutput();
            //确定服务器接收完毕,才能断开连接
            InputStream inputStream = socket.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer2 = new byte[1024];
            int len2;
            while((len=inputStream.read(buffer2))!=-1){
                baos.write(buffer2,0,len);
            }
            System.out.println(baos.toString());
            //5、关闭资源
            baos.close();
            inputStream.close();
            fileInputStream.close();
            os.close();
            socket.close();
        }
    }
    
    //服务端
    public class ServerDemo2 {
        public static void main(String[] args) throws IOException {
            //1、创建服务
            ServerSocket serverSocket = new ServerSocket(9999);
            //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("我接收完毕了,你可以断开了".getBytes());
            //5、关闭资源
            fileOutputStream.close();
            inputStream.close();
            socket.close();
            serverSocket.close();
        }
    }
    
    

    Tomcat

    UDP消息发送

    public class UdpClient1 {
        public static void main(String[] args) throws Exception {
            //1、建立一个Socket
            DatagramSocket socket = new DatagramSocket();
            //2、建个包
            String msg = "你好阿,服务器";
            //发送给谁
            InetAddress localhost = InetAddress.getByName("localhost");
            int port = 9999;
            DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
            //3、发送包
            socket.send(packet);
            //4、关闭流
            socket.close();
        }
    
    public class UdpServer1 {
        public static void main(String[] args) throws IOException {
            //开放端口
            DatagramSocket socket = new DatagramSocket(9999);
            //接收数据包
            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聊天实现

    UDP多线程在线咨询

    URL下载网络资源

  • 相关阅读:
    [易学易懂系列|rustlang语言|零基础|快速入门|(18)|use关键词]
    [易学易懂系列|rustlang语言|零基础|快速入门|(17)|装箱crates]
    [易学易懂系列|rustlang语言|零基础|快速入门|(16)|代码组织与模块化]
    区块链行业访谈:《创世访谈录》
    波卡简介
    [易学易懂系列|rustlang语言|零基础|快速入门|(15)|Unit Testing单元测试]
    GIT分布式代码管理系统
    jenkins介绍及部署tomcat环境、部署Maven项目及密码忘记修改
    Docker安装、命令详情、层级架构、docker服务启动失败解决方法
    ELK日志分析系统部署
  • 原文地址:https://www.cnblogs.com/heibaimao123/p/13784206.html
Copyright © 2020-2023  润新知