Skip to content

Latest commit

 

History

History
166 lines (145 loc) · 6.47 KB

网络编程.md

File metadata and controls

166 lines (145 loc) · 6.47 KB

网络编程

开放式系统互联模(7层模型)

开放式系统互联模型(英语:Open System Interconnection Model,缩写:OSI;简称为OSI模型)是一种概念模型,由国际标准化组织提出,一个试图使各种计算机在世界范围内互连为网络的标准框架

  • 第7层 应用层: 应用层(Application Layer)提供为应用软件而设计的接口,以设置与另一应用软件之间的通信。例如:HTTP、HTTPS、FTP、Telnet、SSH、SMTP、POP3等。
  • 第6层 表示层: 表示层(Presentation Layer)把数据转换为能与接收者的系统格式兼容并适合传输的格式。
  • 第5层 会话层: 会话层(Session Layer)负责在数据传输中设置和维护计算机网络中两台计算机之间的通信连接。
  • 第4层 传输层: 传输层(Transport Layer)把传输表头(TH)加至资料以形成分组。传输表头包含了所使用的协议等发送信息。例如:传输控制协议(TCP)等。
  • 第3层 网络层: 网络层(Network Layer)决定数据的路径选择和转寄,将网络表头(NH)加至数据包,以形成分组。网络表头包含了网络资料。例如:互联网协议(IP)等。
  • 第2层 数据链路层: 数据链路层(Data Link Layer)负责网络寻址、错误侦测和改错。当表头和表尾被加至数据包时,会形成信息框(Data Frame)。数据链表头(DLH)是包含了物理地址和错误侦测及改错的方法。数据链表尾(DLT)是一串指示数据包末端的字符串。例如以太网、无线局域网(Wi-Fi)和通用分组无线服务(GPRS)等。
  • 第1层 物理层: 物理层(Physical Layer)在局域网上发送数据帧(Data Frame),它负责管理电脑通信设备和网络媒体之间的互通。包括了针脚、电压、线缆规范、集线器、中继器、网卡、主机接口卡等。

TCP 协议

UDP协议

TCP 编程

例题: 客服端
public class SocketClient {
  public static void main(String[] args) throws IOException {
    Socket clientSocket = new Socket("127.0.0.1", 6666);
    try (InputStream inputStream = clientSocket.getInputStream(); OutputStream outputStream = clientSocket.getOutputStream()) {
      handle(inputStream, outputStream);
    }
    clientSocket.close();
    System.out.println("disconnected.");
  }

  private static void handle(InputStream inputStream, OutputStream outputStream)
          throws IOException {
    var writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
    var reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
    Scanner scanner = new Scanner(System.in);
    System.out.println("[server] " + reader.readLine());
    for (; ; ) {
      System.out.print(">>> "); // 打印提示
      String s = scanner.nextLine(); // 读取一行输入
      writer.write(s + System.lineSeparator());
      writer.flush();
      String resp = reader.readLine();
      System.out.println("[server]: " + resp);
      if (resp.equals("bye")) {
        break;
      }
    }
  }
}
例题: 服务端
public class SocketServer {
  static class ServerHandler implements Runnable {
    private final Socket socket;

    public ServerHandler(Socket socket) {
      this.socket = socket;
    }

    public void run() {
      try (InputStream inputStream = this.socket.getInputStream();
           OutputStream outputStream = this.socket.getOutputStream()) {
        handle(inputStream, outputStream);
      } catch (Exception e) {
        try {
          this.socket.close();
        } catch (IOException ex) {
          ex.printStackTrace();
        }
        System.out.println("client disconnect");
      }
    }

    private void handle(InputStream inputStream, OutputStream outputStream) throws IOException {
      var reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
      var writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
      writer.write("welcome connect service!\n");
      writer.flush();
      while (true) {
        String line = reader.readLine();
        System.out.println("[client]: " + line);
        if (line.equals("bye")) {
          writer.write("bye\n");
          writer.flush();
          break;
        }
        writer.write("ok: " + ReverseString.reverse(line) + "\n");
        writer.flush();
      }
    }
  }

  public static void main(String[] args) throws IOException {
    int port = 6666;
    ServerSocket serverSocket = new ServerSocket(port);
    System.out.print("server is started! listen on: ");
    System.err.print(port);
    while (true) {
      Socket socket = serverSocket.accept();
      System.out.println("connected from " + socket.getRemoteSocketAddress());
      new Thread(new ServerHandler(socket)).start();
    }
    // TODO
  }
}

UDP 编程

例题: 服务端
public class UDPServer {
  public static void main(String[] args) throws IOException {
    int port = 6666;
    try(DatagramSocket datagramSocket = new DatagramSocket(port)) {
      System.out.println("server started! listen on: " + port);
      byte[] buffer = new byte[1024];
      DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
      datagramSocket.receive(datagramPacket);
      System.out.println("[client]: " + new String(buffer, 0, datagramPacket.getLength()));

      byte[] bytes = ReverseString.reverse(new String(buffer, 0, datagramPacket.getLength()))
              .getBytes(StandardCharsets.UTF_8);
      System.out.println(new String(bytes));
      DatagramPacket dp = new DatagramPacket(bytes, bytes.length, datagramPacket.getAddress(), datagramPacket.getPort());
      datagramSocket.send(dp);
    }
  }
}
例题: 客服端
public class UDPClient {
  public static void main(String[] args) throws IOException {
    DatagramSocket datagramSocket = new DatagramSocket();
    byte[] buffer = "123".getBytes(StandardCharsets.UTF_8);
    DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length, InetAddress.getLocalHost(), 6666);
    datagramSocket.send(datagramPacket);

    byte[] bytes = new byte[1024];
    DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
    datagramSocket.receive(dp);
    System.out.println("[server]: " + new String(bytes, 0, dp.getLength()));
  }
}