想要进行节点与节点间、客户端与服务器端、进程与进程间的通信,需要通过网络IO进行。JAVA通过Socket封装TCP/IP网络协议,进行网络之间的数据传输。

1.首先来回顾一下ISO七层模型和TCP/IP四层协议

 从BIO到Netty

2.了解一下JAVA通过Socket进行网络通信的流程

本地的进程通过PID标识唯一进程号,网络中通过协议+ip地址+端口号标识一个进程号,如:http://10.10.10.10:8080,网络间的进程被唯一标识后,可以进行网络通信。Socket将TCP/IP复杂的操作,封装为简单的接口供应用层使用,实现网络通信。就像文件IO的“打开—读写—关闭”一样,网络间的通信也变成客户端、服务器端可以给自己的”文件“写入内容,供对方读取,通信结束时关闭“文件”。

Socket通信流程:

从BIO到Netty

服务端accept()方法会产生阻塞,等待客户端连接。

3.JAVA中的ServerSocket、Socket类

ServerSocket类:                                                        Socket类:

从BIO到Netty   从BIO到Netty

4.简单的传统BIO通信例子(同步阻塞一问一答式)

服务端代码

package service;

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

public class BIOServerTest {


    public static void main(String[] args) throws IOException {
        new BIOServerTest().bind();
    }

    public void bind() throws IOException {
        ServerSocket server = null;
        try {
            server = new ServerSocket(8000);
            Socket socket = null;
            while (true) {
                socket = server.accept();
                new Thread(new BIOServerHandler(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (server != null) {
                server.close();
            }
        }
    }

    public class BIOServerHandler implements Runnable {
        private Socket socket;

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

        public void run() {
            BufferedReader in = null;
            PrintWriter out = null;
            try {
                in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
                out = new PrintWriter(this.socket.getOutputStream(), true);
                String body = null;
                while (true) {
                    body = in.readLine();
                    if (body == null) {
                        break;
                    }
                    System.out.println("client request " + body);
                    out.println("ok");
                }
            } catch (Exception e) {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
                if (out != null) {
                    out.close();
                }
                if (socket!=null){
                    try {
                        socket.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }
}
View Code

相关文章:

  • 2021-12-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-27
  • 2022-12-23
  • 2021-12-31
猜你喜欢
  • 2021-11-30
  • 2021-06-25
  • 2022-01-11
  • 2021-08-14
  • 2021-10-04
  • 2021-07-01
相关资源
相似解决方案