网络编程_代码实现

253 阅读4分钟

一、InetAddress类(IP)

​ 表示网络编程中的IP地址。

package com.demo.network;

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

public class InetAddressDemo {
    public static void main(String[] args) {
        try {
            // 根据指定IP地址获取对象
            InetAddress ipInetAddress = InetAddress.getByName("192.168.31.43");
            // 根据指定域名获取对象
            InetAddress baiduInetAddress = InetAddress.getByName("www.baidu.com");
            // 获取本地对象
            InetAddress localHost = InetAddress.getLocalHost();

            /* localHost对象、打印如下: 主机名/IP地址
              SD-20200613OGGB/192.168.31.43
            * */
            System.out.println(localHost);

            /* getAddress()、打印字节数组如下:
              [B@4554617c
            * */
            System.out.println(localHost.getAddress());

            /* getHostName()、打印如下:主机名/域名
              SD-20200613OGGB
            * */
            System.out.println(localHost.getHostName());

            /* getHostAddress()、打印如下:IP地址
              192.168.31.43
            * */
            System.out.println(localHost.getHostAddress());

            /* getCanonicalHostName()、打印如下:规范的主机名
              SD-20200613OGGB
            * */
            System.out.println(localHost.getCanonicalHostName());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

二、InetSocketAddress类(端口号)

​ 表示网络编程中的端口号。

package com.demo.network;

import java.net.InetSocketAddress;

public class InetSocketAddressDemo {
    public static void main(String[] args) {
        // 获取本地tomcat的对象
        InetSocketAddress localhost = new InetSocketAddress("localhost", 8080);

        /* getHostName、打印如下: 主机名/IP地址
        *  localhost
        * */
        System.out.println(localhost.getHostName());

        /* getAddress、打印如下: 主机名/IP地址
         *  localhost/127.0.0.1
         * */
        System.out.println(localhost.getAddress());

        /* getPort、打印如下: 主机名/IP地址
         *  8080
         * */
        System.out.println(localhost.getPort());
    }
}

三、TCP发送文字Demo

  • TcpClientDemo.java (TCP客户端)
package com.demo.network;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClientDemo {
    public static void main(String[] args) {
        Socket client = null;
        OutputStream os = null;
        try {
            // 创建Socket,连接服务器
            client = new Socket(InetAddress.getLocalHost(), 8001);
            // 创建输出流
            os = client.getOutputStream();
            // 输入内容
            os.write("你好,服务器!".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (os != null) {
                    os.close();
                }
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • TcpServerDemo.java (TCP服务端)
package com.demo.network;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServerDemo {
    public static void main(String[] args) {
        ServerSocket server = null;
        Socket accept = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            // 打开服务器端口,创建ServerSocket
            server = new ServerSocket(8001);
            // 等待客户端接入
            accept = server.accept();
            // 读取客户端的信息
            is = accept.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 (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (baos != null) {
                    baos.close();
                }
                if (is != null) {
                    is.close();
                }
                if (accept != null) {
                    accept.close();
                }
                if (server != null) {
                    server.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

四、TCP发送文件Demo

  • TcpClientDemo.java (TCP客户端)
package com.demo.network;

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

public class TcpClientDemo {
    public static void main(String[] args) {
        Socket client = null;
        OutputStream os = null;
        InputStream is = null;
        FileInputStream fis = null;
        ByteArrayOutputStream baos = null;
        try {
            // 连接服务器
            client = new Socket(InetAddress.getLocalHost(), 8001);
            // 读取文件
            fis = new FileInputStream(new File("G:\\1.png"));
            // 创建输出流
            os = client.getOutputStream();
            // 写出文件
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            // 通知服务器传输完成
            client.shutdownOutput();
            // 获取服务器信息
            is = client.getInputStream();
            // 读取信息
            baos = new ByteArrayOutputStream();
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            System.out.println(baos.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (baos != null) {
                    baos.close();
                }
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
                if (fis != null) {
                    fis.close();
                }
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • TcpServerDemo.java (TCP服务端)
package com.demo.network;

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

public class TcpServerDemo {
    public static void main(String[] args) {
        ServerSocket server = null;
        Socket accept = null;
        InputStream is = null;
        OutputStream os = null;
        FileOutputStream fos = null;
        try {
            // 创建服务器
            server = new ServerSocket(8001);
            // 监听客户端信息
            accept = server.accept();
            // 获取输入流
            is = accept.getInputStream();
            // 读取文件输出流并保存
            fos = new FileOutputStream(new File("G:\\2.png"));
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            // 通知客户端文件以及收到
            os = accept.getOutputStream();
            os.write("文件已经收到!".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭资源
                if (os != null) {
                    os.close();
                }
                if (fos != null) {
                    fos.close();
                }
                if (is != null) {
                    is.close();
                }
                if (accept != null) {
                    accept.close();
                }
                if (server != null) {
                    server.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

五、UDP发送文字Demo

  • UdpSenderDemo.java (UDP发送端)
package com.demo.network;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpSenderDemo {
    public static void main(String[] args) {
        DatagramSocket sender = null;
        try {
            // 建立连接
            sender = new DatagramSocket();
            // 包要素 - 内容
            String message = "你好,朋友!";
            byte[] data = message.getBytes();
            // 包要素 - ip地址
            InetAddress ipAddress = InetAddress.getLocalHost();
            // 包要素 - 端口号
            int port = 8001;
            // 创建包
            DatagramPacket packet = new DatagramPacket(
                    data, 0, data.length, ipAddress, port);
            // 发送包
            sender.send(packet);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != sender) {
                    sender.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
  • UdpReceiverDemo.java (UDP接收端)
package com.demo.network;

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

public class UdpReceiverDemo {
    public static void main(String[] args) {
        DatagramSocket receiver = null;
        try {
            // 建立连接,开发端口
            receiver = new DatagramSocket(8001);
            // 接收数据
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
            receiver.receive(packet);
            // 读取数据
            String message = new String(packet.getData(), 0, packet.getLength());
            System.out.println(message);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != receiver) {
                    receiver.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

六、UDP聊天Demo

  • UdpChatSender.java (聊天发送端)
package com.demo.network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpChatSender implements Runnable{
    DatagramSocket socket = null;
    InetAddress toIp = null;
    Integer toPort = 0;
    Scanner sc = null;

    public UdpChatSender(InetAddress toIp, Integer toPort) {
        try {
            this.socket = new DatagramSocket();
            this.toIp = toIp;
            this.toPort = toPort;
            this.sc = new Scanner(System.in);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        try {
            while (true) {
                String message = sc.nextLine();
                if ("quit".equals(message)) {
                    break;
                }
                DatagramPacket packet = new DatagramPacket(
                        message.getBytes(), 0, message.getBytes().length, toIp, toPort);
                socket.send(packet);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != socket) {
                socket.close();
            }
        }
    }
}
  • UdpChatReceiver.java (聊天接收端)
package com.demo.network;

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

public class UdpChatReceiver implements Runnable{
    DatagramSocket socket = null;
    byte[] buffer = new byte[1024];

    public UdpChatReceiver(Integer fromPort) {
        try {
            this.socket = new DatagramSocket(fromPort);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        try {
            while (true) {
                DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
                socket.receive(packet);
                String message = new String(packet.getData());
                if ("quit".equals(message)) {
                    break;
                }
                System.out.println(packet.getPort() + "  " + new Date());
                System.out.println(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != socket) {
                socket.close();
            }
        }
    }
}
  • UdpChatUserOne.java (UDP用户One)
package com.demo.network;

import java.net.InetAddress;

public class UdpChatUserOne {
    public static void main(String[] args) {
        try {
            InetAddress toIp = InetAddress.getLocalHost();
            Integer toPort = 8001;
            Integer fromPort = 8002;
            new Thread(new UdpChatSender(toIp, toPort)).start();
            new Thread(new UdpChatReceiver(fromPort)).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • UdpChatUserTwo.java (UDP用户Two)
package com.demo.network;

import java.net.InetAddress;

public class UdpChatUserTwo {
    public static void main(String[] args) {
        try {
            InetAddress toIp = InetAddress.getLocalHost();
            Integer toPort = 8002;
            Integer fromPort = 8001;
            new Thread(new UdpChatSender(toIp, toPort)).start();
            new Thread(new UdpChatReceiver(fromPort)).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 效果演示

七、URL类

  • 统一资源标识符,格式:protocol://host:port/path?query#fragment
package com.demo.network;

import java.net.URL;

public class URLDemo {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://localhost:8080/demo/index.jsp?userName=admin&password=123456");
            /* getProtocol()、打印如下
             * http
             */
            System.out.println(url.getProtocol());
            /* getHost()、打印如下
             * localhost
             */
            System.out.println(url.getHost()); //获取URL的主机名
            /* getPort()、打印如下
             * 8080
             */
            System.out.println(url.getPort()); //获取URL的端口号
            /* getPath()、打印如下
             * /demo/index.jsp
             */
            System.out.println(url.getPath()); //获取URL的文件路径
            /* getFile()、打印如下
             * /demo/index.jsp?userName=admin&password=123456
             */
            System.out.println(url.getFile()); //获取URL的文件名
            /* getQuery()、打印如下
             * userName=admin&password=123456
             */
            System.out.println(url.getQuery()); //获取URL的查询名
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}