计算机网络 学习笔记

IP

IP 地址 InetAddress

  • 唯一定位一台网络上计算机
  • 127.0.0.1:本机 localhost
  • IP 地址分类:
    IPV4 / IPV6(128位 8个无符号整数)
    公网(互联网) / 私网(局域网)
package com.jarvis.lesson01;

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

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("www.baidu.com");
            System.out.println(inetAddress2);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

端口
  • 不同的进程有不同的端口号,用来区分软件
  • 被规定 0 ~ 65535
  • 单个协议下,端口号不能冲突
  • 端口分类:
    • 公有端口 0 ~ 1023
      • HTTP:80
      • HTTPS:443
      • FTP:21
      • Telent:23
    • 程序注册端口:1024 ~ 49151 分配给用户或者程序
      • Tomcat:8080
      • MySQL:3306
      • Oracle:1521
    • 动态、私有端口:49152 ~ 15535
package com.jarvis.lesson01;

import java.net.InetSocketAddress;

public class TestInetSocketAddress {
    public static void main(String[] args) {
        InetSocketAddress inetSocketAddress1 = new InetSocketAddress("127.0.0.1", 8080);
        InetSocketAddress inetSocketAddress2 = new InetSocketAddress("localhost", 8080);
        System.out.println(inetSocketAddress1);
        System.out.println(inetSocketAddress2);

        System.out.println(inetSocketAddress1.getAddress());
        System.out.println(inetSocketAddress1.getHostName());
        System.out.println(inetSocketAddress1.getPort());
    }
}

TCP

客户端

package com.jarvis.lesson02;

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

public class TCPServerDemo01 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            // 服务器得有一个地址
            serverSocket = new ServerSocket(9999);
            while (true){
                // 等待客户端连接
                socket = serverSocket.accept();
                // 读取客户端消息
                is = socket.getInputStream();
                // 管道流
                byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while((len = is.read(buffer)) != -1){
                    byteArrayOutputStream.write(buffer, 0, len);
                }
                System.out.println(byteArrayOutputStream.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if(byteArrayOutputStream != null){
                try {
                    byteArrayOutputStream.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 com.jarvis.lesson02;

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

public class TCPClientDemo01 {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        try {
            // 要知道服务器的地址
            InetAddress severIP = InetAddress.getByName("127.0.0.1");
            // 端口号
            int port = 9999;
            // 创建 socket 连接
            socket = new Socket(severIP, port);
            // 发送消息
            os = socket.getOutputStream();
            os.write("Hello".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();
                }
            }
        }
    }
}

文件上传

服务器

package com.jarvis.lesson02;

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

public class TCPServerDemo02 {
    public static void main(String[] args) throws Exception {
        // 创建服务
        ServerSocket serverSocket = new ServerSocket(9999);
        // 监听客户端连接
        // 阻塞式监听,会一直等待客户端连接
        Socket socket = serverSocket.accept();
        // 获取输入流
        InputStream inputStream = socket.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream(new File("receive.jpg"));
        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());
        // 关闭资源
        outputStream.close();
        fileOutputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
    }
}

客户端

package com.jarvis.lesson02;

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

public class TCPClientDemo02 {
    public static void main(String[] args) throws Exception {
        // 创建 socket 连接
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
        // 创建一个输出流
        OutputStream outputStream = socket.getOutputStream();
        // 读取文件
        FileInputStream fileInputStream = new FileInputStream(new File("2020.1.16BurgerKing.jpg"));
        // 写出文件
        byte[] buffer = new byte[1024];
        int len;
        while((len = fileInputStream.read(buffer)) != -1){
            outputStream.write(buffer, 0, len);
        }
        // 通知服务器已经传输完毕
        socket.shutdownOutput();
        // 确定服务器接受完毕,才能断开连接
        InputStream inputStream = socket.getInputStream();
        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.toString());
        // 关闭资源
        byteArrayOutputStream.close();
        inputStream.close();
        fileInputStream.close();
        outputStream.close();
        socket.close();
    }
}

Tomcat

服务器:

  • 自定义 S
  • Tomcat S
    客户端:
  • 自定义 C
  • 浏览器 B
UDP

发送端

package com.jarvis.lesson03;

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

public class UDPClientDemo01 {
    public static void main(String[] args) throws Exception {
        // 建立一个 socket
        DatagramSocket socket = new DatagramSocket();
        // 建立一个包
        String msg = "Hello";
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9090;
        DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
        // 发送这个包
        socket.send(datagramPacket);
        // 关闭流
        socket.close();
    }
}

接收端

package com.jarvis.lesson03;

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

// 等待客户端的连接
public class UDPServerDemo01 {
    public static void main(String[] args) throws Exception {
        // 开放端口
        DatagramSocket socket = new DatagramSocket(9090);
        // 接收数据
        byte[] buffer = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length);
        socket.receive(datagramPacket);// 阻塞接收
        System.out.println(new String(datagramPacket.getData(), 0, datagramPacket.getLength()));
        System.out.println(datagramPacket.getAddress().getHostAddress());
        // 关闭连接
        socket.close();
    }
}

循环发送消息
package com.jarvis.lesson03.chat;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;

public class UDPSenderDemo01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(9999);

        // 准备数据,从控制台读取 System.in
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while(true){
            String data = reader.readLine();
            DatagramPacket datagramPacket = new DatagramPacket(data.getBytes(), 0, data.getBytes().length, new InetSocketAddress("localhost", 6666));
            socket.send(datagramPacket);
            if(data.equals("bye")) break;
        }
        socket.close();
    }
}

循环接收消息
package com.jarvis.lesson03.chat;

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

public class UDPReceiverDemo01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(6666);
        while(true){
            byte[] buffer = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length);
            socket.receive(datagramPacket);// 阻塞式接收包裹

            // 读取数据 + 断开连接
            byte[] data = datagramPacket.getData();
            String receiveData = new String(data, 0, datagramPacket.getLength());
            System.out.println(receiveData);
            if(receiveData.equals("bye")) break;

        }
        socket.close();
    }
}

聊天(多线程)
package com.jarvis.lesson03.chat;

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

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

    public TalkSender(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() {
        try{
            while(true){
                String data = reader.readLine();
                DatagramPacket datagramPacket = new DatagramPacket(data.getBytes(), 0, data.getBytes().length, new InetSocketAddress(this.toIP, this.toPort));
                socket.send(datagramPacket);
                if(data.equals("bye")) break;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        socket.close();
    }
}

package com.jarvis.lesson03.chat;

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

public class TalkReceiver implements Runnable{
    DatagramSocket socket = null;
    private int port;
    private String msgFrom;

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

    @Override
    public void run() {
        while(true){
            try {
                byte[] buffer = new byte[1024];
                DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length);
                socket.receive(datagramPacket);// 阻塞式接收包裹

                // 读取数据 + 断开连接
                byte[] data = datagramPacket.getData();
                String receiveData = new String(data, 0, datagramPacket.getLength());
                System.out.println(msgFrom + ": " + receiveData);
                if(receiveData.equals("bye")) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}

package com.jarvis.lesson03.chat;

public class TalkStudent {
    public static void main(String[] args) {
        // 开启两个线程
        new Thread(new TalkSender(7777, "localhost", 9999)).start();
        new Thread(new TalkReceiver(8888, "Teacher")).start();
    }
}

package com.jarvis.lesson03.chat;

public class TalkTeacher {
    public static void main(String[] args) {
        new Thread(new TalkSender(6666, "localhost", 8888)).start();
        new Thread(new TalkReceiver(9999, "Student")).start();
    }
}

URL

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

package com.jarvis.lesson04;

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

public class URLDemo01 {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=jarvis");
        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());// 参数
    }
}

package com.jarvis.lesson04;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class URLDownload {
    public static void main(String[] args) throws Exception {
        // 下载地址
        URL url = new URL("https://m701.music.126.net/20210420142930/3c4efca75974029c2494500a8e41dd9c/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/5834087098/9ceb/ccef/b926/b10f27123a21733438e379a4682c5a2c.m4a");
        // 连接到这个资源
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream("music.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();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值