Java 网络编程

一、网络编程概述

1、计算机网络

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

2、网络编程的目的

无线电台…传播交流信息,数据交换,通信。

3、网络编程中的要素

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

二、IP和端口号

1、IP

IP 地址:InetAddress

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

  • 127.0.0.1: 本机localhost

ip地址的分类

  • IPV4/IPV6
    • IPV4:127.0.0.1(长度32bit)
    • IPV6: 3287:0fe0:0000:0000:0000:0fa1:ffff:0234(长度128bit)
  • 公网(互联网)—私网(局域网)
    • ABCD地址
    • 192.168.xx.xx,专门给组织内部使用。
public class TestInetAddress {
    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);
            // 查询网站IP地址
            InetAddress inetAddress = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress);
            // 常用方法
            System.out.println(inetAddress.getCanonicalHostName());    // 规范的名字
            System.out.println(inetAddress.getHostAddress());  // IP
            System.out.println(inetAddress.getHostName()); // 域名,或者自己电脑的名字
        }catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

2、端口号

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

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

  • 被规定0~65535

  • TCP,UDP:65535*2个端口 tcp:80 udp:80 单个协议下,端口号不能冲突

端口分类

  • 共有端口 0~1023 内置的进程使用
    • HTTP:80
    • HTTP:443 (访问https://www.baidu.com:443 访问的还是百度)
    • FTP:21
    • TELENT:23
  • 程序注册端口:1014-49151,分配给用户和程序
    • Tomcat:8080
    • MySql:3306
    • Oracle:1521
  • 动态、私有端口:49152~65535

常用DOS命令 

netstat -ano #查看所有的端口
netstat -nao|findstr "7808" #查看指定的端口
tasklist|findstr "8696"
public class TestInetSocketAddress {
    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/IP协议簇:实际上是一组协议

  • TCP:用户传输协议
  • UDP:用户数据报协议
  • IP:网络互联协议

TCP UDP 对比

  • TCP:打电话

    • 连接,稳定

    • 三次握手,四次挥手

    • 客户端、服务器

    • 传输完成,释放连接,效率低

  • UDP:发短信

    • 不连接,不稳定
    • 客户端、服务端:没有明确的界限
    • 不管有没有准备好,都可以发给你

1、TCP

(1)实现聊天

注意:先启动服务器端,再启动客户端

客户端

  • 连接服务器 Socket
  • 发送消息
public class TCPClientDemo {
    public static void main(String[] args) {
        Socket accept = null;
        OutputStream os = null;
        try {
            // 1.要知道服务器的地址
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            int port = 9999;
            // 2.创建一个socket链接
            accept = new Socket(inetAddress,port);
            // 3.发送信息IO流
            os = accept.getOutputStream();
            os.write("你好,世界!".getBytes());
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            // 关闭资源
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(accept != null){
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

服务器端

  • 建立服务的端口 ServerSocket
  • 等待的用户的连接 accept
  • 接收用户的消息
public class TCPServerDemo {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try{
            // 1.有一个地址
            serverSocket = new ServerSocket(9999);
            // 2.等待客户端连接过来
            socket = serverSocket.accept();
            // 3.读取客户端的消息
            is = socket.getInputStream();
            // 管道流
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            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();
                }
            }
        }
    }
}

(2)实现文件上传

客户端

public class TCPClientDemo {
    public static void main(String[] args) throws Exception {
        // 1.建立连接
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);
        // 2.创建输出流
        OutputStream os = socket.getOutputStream();
        // 3.读取文件
        FileInputStream stream = new FileInputStream(new File("wdl.jpg"));
        // 4.输出测试文件
        byte[] buffer = new byte[1024];
        int len = 0;
        while((len = stream.read(buffer)) != -1){
            os.write(buffer,0,len);
        }
        // 5.通知服务器已发送完成
        socket.shutdownOutput();
        // 6.确定服务器已经收到,断开连接
        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer2 = new byte[1024];
        int len2 = 0;
        while((len2 = stream.read(buffer2)) != -1){
            byteArrayOutputStream.write(buffer2,0,len2);
        }
        System.out.println(byteArrayOutputStream);
        // 7.关闭流
        byteArrayOutputStream.close();
        inputStream.close();
        stream.close();
        os.close();
        socket.close();
    }
}

服务器端

public class TCPServerDemo {
    public static void main(String[] args) throws Exception{
        // 1.创建一个服务器地址
        ServerSocket socket = new ServerSocket(9000);
        // 2.监听客户连接
        Socket accept = socket.accept();    // 阻塞式监听,能等待用户连进来
        // 3.获取输入流
        InputStream is = accept.getInputStream();
        // 4.确定存放文件的位置
        FileOutputStream fileOutputStream = new FileOutputStream("wq.jpg");
        // 5.写入文件
        byte[] buffer = new byte[1024];
        int len = 0;
        while((len = is.read(buffer)) != -1){
            fileOutputStream.write(buffer,0,len);
        }
        // 6.通知客户端收集完毕
        OutputStream outputStream = accept.getOutputStream();
        outputStream.write("服务器已经收集成功,请断开连接!".getBytes());
        // 7.关闭流
        outputStream.close();
        fileOutputStream.close();
        is.close();
        accept.close();
        socket.close();
    }
}

2、UDP

(1)消息发送

// 不需要连接服务器
public class UDPClientDemo {
    public static void main(String[] args) throws Exception{
        // 1.建立一个Socket
        DatagramSocket socket = new DatagramSocket();
        // 2.建个包
        String msg = "你好服务器!";
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9090;
        // 数据,数据的长度起始,要发送给谁
        DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0,msg.getBytes().length,localhost,port);
        // 3.发送包
        socket.send(packet);
        // 4.关闭流
        socket.close();
    }
}
// 需要客户端的链接
public class UDPServerDemo01 {
    public static void main(String[] args) throws Exception{
        // 1.开放端口
        DatagramSocket socket = new DatagramSocket(9090);
        // 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()));
        // 3.关闭连接
        socket.close();
    }
}

(2)循环发送消息

public class UDPSenderDemo {
    public static void main(String[] args) throws Exception{
        DatagramSocket socket = new DatagramSocket(8888);
        // 准备数据:控制台读取
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while(true) {
            String data = reader.readLine();
            byte[] buffer = data.getBytes();
            DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length, new InetSocketAddress("localhost", 9090));
            // 发送包
            socket.send(packet);
            if (data.equals("bye")) {
                break;
            }
        }
        // 关闭socket
        socket.close();
    }
}
public class UDPReceiveDemo {
    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);
            byte[] data = packet.getData();
            String receiveData = new String(data);
            System.out.println(receiveData);
            if (receiveData.equals("bye")) {
                break;
            }
        }
        // 关闭socket
        socket.close();
    }
}

四、URL

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

  • DNS域名解析

协议:// ip地址:端口号/项目名/资源
public class URLDemo {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://localhost:8080/helloword/insex.jsp?username=subeily&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()); // 参数
    }
}

下载文件

public class URLDemo {
    public static void main(String[] args) throws Exception{
        // 1.下载地址
        URL url = new URL("http://localhost:8080/wdl/123.txt");
        // 2.连接到这个资源 HTTP
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream is = urlConnection.getInputStream();
        FileOutputStream stream = new FileOutputStream(new File("same.txt"));
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = is.read(bytes)) != -1){
            stream.write(bytes,0,len);
        }
        stream.close();
        is.close();
        urlConnection.disconnect();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值