1. 程式人生 > 其它 >網路程式設計與通訊原理

網路程式設計與通訊原理

目錄

總感覺這個概念,和研發有點脫節;

一、基礎概念

不同裝置之間通過網路進行資料傳輸,並且基於通用的網路協議作為多種裝置的相容標準,稱為網路通訊;

以C/S架構來看,在一次請求當中,客戶端和服務端進行資料傳輸的互動時,在不同階段和層次中需要遵守的網路通訊協議也不一樣;

應用層:HTTP超文字傳輸協議,基於TCP/IP通訊協議來傳遞資料;

傳輸層:TCP傳輸控制協議,採用三次握手的方式建立連線,形成資料傳輸通道;

網路層:IP協議,作用是把各種傳輸的資料包傳送給請求的接收方;

通訊雙方進行互動時,傳送方資料在各層傳輸時,每通過一層就會新增該層的首部資訊;接收方與之相反,每通過一次就會刪除該層的首部資訊;

二、JDK原始碼

java.net原始碼包中,提供了與網路程式設計相關的基礎API;

1、InetAddress

封裝了對IP地址的相關操作,在使用該API之前可以先檢視本機的hosts的對映,Linux系統中在/etc/hosts路徑下;

import java.net.InetAddress;
public class TestInet {

    public static void main(String[] args) throws Exception {
        // 獲取本機 InetAddress 物件
        InetAddress localHost = InetAddress.getLocalHost();
        printInetAddress(localHost);
        // 獲取指定域名 InetAddress 物件
        InetAddress inetAddress = InetAddress.getByName("www.baidu.com");
        printInetAddress(inetAddress);
        // 獲取本機配置 InetAddress 物件
        InetAddress confAddress = InetAddress.getByName("nacos-service");
        printInetAddress(confAddress);
    }

    public static void printInetAddress (InetAddress inetAddress){
        System.out.println("InetAddress:"+inetAddress);
        System.out.println("主機名:"+inetAddress.getHostName());
        System.out.println("IP地址:"+inetAddress.getHostAddress());
    }
}

2、URL

統一資源定位符,URL一般包括:協議、主機名、埠、路徑、查詢引數、錨點等,路徑+查詢引數,也被稱為檔案;

import java.net.URL;
public class TestURL {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://www.baidu.com:80/s?wd=Java#bd") ;
        printURL(url);
    }
    private static void printURL (URL url){
        System.out.println("協議:" + url.getProtocol());
        System.out.println("域名:" + url.getHost());
        System.out.println("埠:" + url.getPort());
        System.out.println("路徑:" + url.getPath());
        System.out.println("引數:" + url.getQuery());
        System.out.println("檔案:" + url.getFile());
        System.out.println("錨點:" + url.getRef());
    }
}

3、HttpURLConnection

作為URLConnection的抽象子類,用來處理針對Http協議的請求,可以設定連線超時、讀取超時、以及請求的其他屬性,是服務間通訊的常用方式;

public class TestHttp {
    public static void main(String[] args) throws Exception {
        // 訪問 網址 內容
        URL url = new URL("https://www.jd.com");
        HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
        printHttp(httpUrlConnection);

        // 請求 服務 介面
        URL api = new URL("http://localhost:8082/info/99");
        HttpURLConnection apiConnection = (HttpURLConnection) api.openConnection();
        apiConnection.setRequestMethod("GET");
        apiConnection.setConnectTimeout(3000);
        printHttp(apiConnection);
    }

    private static void printHttp (HttpURLConnection httpUrlConnection) throws Exception{
        try (InputStream inputStream = httpUrlConnection.getInputStream()) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line ;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}

三、通訊程式設計

1、Socket

Socket也被稱為套接字,是兩臺裝置之間通訊的端點,會把網路連線當成流處理,則資料以IO形式傳輸,這種方式在當前被普遍採用;

從網路程式設計直接跳到Socket套接字,概念上確實有較大跨度,概念過度抽象時,可以看看原始碼的核心結構,在理解時會輕鬆很多,在JDK中重點看SocketImpl抽象類;

public abstract class SocketImpl implements SocketOptions {
    // Socket物件,客戶端和服務端
    Socket socket = null;
    ServerSocket serverSocket = null;
    // 套接字的檔案描述物件
    protected FileDescriptor fd;
    // 套接字的路由IP地址
    protected InetAddress address;
    // 套接字連線到的遠端主機上的埠號
    protected int port;
    // 套接字連線到的本地埠號
    protected int localport;
}

套接字的抽象實現類,是實現套接字的所有類的公共超類,可以用於建立客戶端和伺服器套接字;

所以到底如何理解Socket概念?從抽象類中來看,套接字就是指代網路通訊中系統資源的核心標識,比如通訊方IP地址、埠、狀態等;

2、SocketServer

建立Socket服務端,並且在8989埠監聽,接收客戶端的連線請求和相關資訊,並且響應客戶端,傳送指定的資料;

public class SocketServer {
    public static void main(String[] args) throws Exception {
        // 1、建立Socket服務端
        ServerSocket serverSocket = new ServerSocket(8989);
        System.out.println("socket-server:8989,waiting connect...");
        // 2、方法阻塞等待,直到有客戶端連線
        Socket socket = serverSocket.accept();
        System.out.println("socket-server:8989,get connect:"+socket.getPort());
        // 3、輸入流,輸出流
        InputStream inStream = socket.getInputStream();
        OutputStream outStream = socket.getOutputStream();
        // 4、資料接收和響應
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen=inStream.read(buf)) != -1){
            // 接收資料
            String readVar = new String(buf, 0, readLen) ;
            if ("exit".equals(readVar)){
                break ;
            }
            System.out.println("recv:"+readVar+";time:"+DateTime.now().toString(DatePattern.NORM_DATETIME_PATTERN));
            // 響應資料
            outStream.write(("resp-time:"+DateTime.now().toString(DatePattern.NORM_DATETIME_PATTERN)).getBytes());
        }
        // 5、資源關閉
        outStream.close();
        inStream.close();
        socket.close();
        serverSocket.close();
        System.out.println("socket-server:8989,exit...");
    }
}

需要注意的是步驟2輸出的埠號是隨機不確定的,結合jpslsof -i tcp:port命令檢視程序和埠號的佔用情況;

3、SocketClient

建立Socket客戶端,並且連線到服務端,讀取命令列輸入的內容併發送到服務端,並且輸出服務端的響應資料;

public class SocketClient {
    public static void main(String[] args) throws Exception {
        // 1、建立Socket客戶端
        Socket socket = new Socket(InetAddress.getLocalHost(), 8989);
        System.out.println("server-client,connect to:8989");
        // 2、輸入流,輸出流
        OutputStream outStream = socket.getOutputStream();
        InputStream inStream = socket.getInputStream();
        // 3、資料傳送和響應接收
        int readLen = 0;
        byte[] buf = new byte[1024];
        while (true){
            // 讀取命令列輸入
            BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
            String iptLine = bufReader.readLine();
            if ("exit".equals(iptLine)){
                break;
            }
            // 傳送資料
            outStream.write(iptLine.getBytes());
            // 接收資料
            if ((readLen = inStream.read(buf)) != -1) {
                System.out.println(new String(buf, 0, readLen));
            }
        }
        // 4、資源關閉
        inStream.close();
        outStream.close();
        socket.close();
        System.out.println("socket-client,get exit command");
    }
}

測試結果:整個流程在沒有收到客戶端的exit退出指令前,會保持連線的狀態,並且可以基於位元組流模式,進行持續的資料傳輸;

4、字元流使用

基於上述的基礎案例,採用字元流的方式進行資料傳輸,客戶端和服務端只進行一次簡單的互動;

-- 1、客戶端
BufferedReader bufReader = new BufferedReader(new InputStreamReader(inStream));
BufferedWriter bufWriter = new BufferedWriter(new OutputStreamWriter(outStream));
// 客戶端傳送資料
bufWriter.write("hello,server");
bufWriter.newLine();
bufWriter.flush();
// 客戶端接收資料
System.out.println("client-read:"+bufReader.readLine());

-- 2、服務端
BufferedReader bufReader = new BufferedReader(new InputStreamReader(inStream));
BufferedWriter bufWriter = new BufferedWriter(new OutputStreamWriter(outStream));
// 服務端接收資料
System.out.println("server-read:"+bufReader.readLine());
// 服務端響應資料
bufWriter.write("hello,client");
bufWriter.newLine();
bufWriter.flush();

5、檔案傳輸

基於上述的基礎案例,客戶端向服務端傳送圖片檔案,服務端完成檔案的讀取和儲存,在處理完成後給客戶端傳送結果描述;

-- 1、客戶端
// 客戶端傳送圖片
FileInputStream fileStream = new FileInputStream("Local_File_Path/jvm.png");
byte[] bytes = new byte[1024];
int i = 0;
while ((i = fileStream.read(bytes)) != -1) {
    outStream.write(bytes);
}
// 寫入結束標記,禁用此套接字的輸出流,之後再使用輸出流會拋異常
socket.shutdownOutput();
// 接收服務端響應結果
System.out.println("server-resp:"+new String(bytes,0,readLen));

-- 2、服務端
// 接收客戶端圖片
FileOutputStream fileOutputStream = new FileOutputStream("Local_File_Path/new_jvm.png");
byte[] bytes = new byte[1024];
int i = 0;
while ((i = inStream.read(bytes)) != -1) {
    fileOutputStream.write(bytes, 0, i);
}
// 響應客戶端檔案處理結果
outStream.write("file-save-success".getBytes());

6、TCP協議

Socket網路程式設計是基於TCP協議的,TCP傳輸控制協議是一種面向連線的、可靠的、基於位元組流的傳輸層通訊協議,在上述案例中側重基於流的資料傳輸,其中關於連線還涉及兩個核心概念:

三次握手:建立連線的過程,在這個過程中進行了三次網路通訊,當連線處於建立的狀態,就可以進行正常的通訊,即資料傳輸;四次揮手:關閉連線的過程,呼叫close方法,即連線使用結束,在這個過程中進行了四次網路通訊;

四、Http元件

在服務通訊時依賴網路,而對於程式設計來說,更常見的是的Http的元件,在微服務架構中,涉及到Http元件工具有很多,例如Spring框架中的RestTemplate,Feign框架支援ApacheHttp和OkHttp;下面圍繞幾個常用的元件編寫測試案例;

1、基礎介面

@RestController
public class BizWeb {

    @GetMapping("/getApi/{id}")
    public Rep<Integer> getApi(@PathVariable Integer id){
        log.info("id={}",id);
        return Rep.ok(id) ;
    }

    @GetMapping("/getApi_v2/{id}")
    public Rep<Integer> getApiV2(HttpServletRequest request,
                                 @PathVariable Integer id,
                                 @RequestParam("name") String name){
        String token = request.getHeader("Token");
        log.info("token={},id={},name={}",token,id,name);
        return Rep.ok(id) ;
    }

    @PostMapping("/postApi")
    public Rep<IdKey> postApi(HttpServletRequest request,@RequestBody IdKey idKey){
        String token = request.getHeader("Token");
        log.info("token={},idKey={}", token,JSONUtil.toJsonStr(idKey));
        return Rep.ok(idKey) ;
    }

    @PutMapping("/putApi")
    public Rep<IdKey> putApi(@RequestBody IdKey idKey){
        log.info("idKey={}", JSONUtil.toJsonStr(idKey));
        return Rep.ok(idKey) ;
    }

    @DeleteMapping("/delApi/{id}")
    public Rep<Integer> delApi(@PathVariable Integer id){
        log.info("id={}",id);
        return Rep.ok(id) ;
    }
}

2、ApacheHttp

public class TestApacheHttp {

    private static final String BASE_URL = "http://localhost:8083" ;
    public static void main(String[] args) {
        BasicHeader header = new BasicHeader("Token","ApacheSup") ;

        // 1、傳送Get請求
        Map<String,String> param = new HashMap<>() ;
        param.put("name","cicada") ;
        Rep getRep = doGet(BASE_URL+"/getApi_v2/3",header,param, Rep.class);
        System.out.println("get:"+getRep);

        // 2、傳送Post請求
        IdKey postBody = new IdKey(1,"id-key-我") ;
        Rep postRep = doPost (BASE_URL+"/postApi", header, postBody, Rep.class);
        System.out.println("post:"+postRep);
    }
    /**
     * 構建HttpClient物件
     */
    private static CloseableHttpClient buildHttpClient (){
        // 請求配置
        RequestConfig reqConfig = RequestConfig.custom().setConnectTimeout(6000).build();
        return HttpClients.custom()
                .setDefaultRequestConfig(reqConfig).build();
    }
    /**
     * 執行Get請求
     */
    public static <T> T doGet (String url, Header header, Map<String,String> param,
                               Class<T> repClass) {
        // 建立Get請求
        CloseableHttpClient httpClient = buildHttpClient();
        HttpGet httpGet = new HttpGet();
        httpGet.addHeader(header);
        try {
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            httpGet.setURI(builder.build());
            // 請求執行
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                // 結果轉換
                String resp = EntityUtils.toString(httpResponse.getEntity());
                return JSONUtil.toBean(resp, repClass);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(httpClient);
        }
        return null;
    }
    /**
     * 執行Post請求
     */
    public static <T> T doPost (String url, Header header, Object body,Class<T> repClass) {
        // 建立Post請求
        CloseableHttpClient httpClient = buildHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(header);
        StringEntity conBody = new StringEntity(JSONUtil.toJsonStr(body),ContentType.APPLICATION_JSON);
        httpPost.setEntity(conBody);
        try {
            // 請求執行
            HttpResponse httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                // 結果轉換
                String resp = EntityUtils.toString(httpResponse.getEntity());
                return JSONUtil.toBean(resp, repClass);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IoUtil.close(httpClient);
        }
        return null;
    }
}

3、OkHttp

public class TestOkHttp {

    private static final String BASE_URL = "http://localhost:8083" ;
    public static void main(String[] args) {
        Headers headers = new Headers.Builder().add("Token","OkHttpSup").build() ;

        // 1、傳送Get請求
        Rep getRep = execute(BASE_URL+"/getApi/1", Method.GET.name(), headers, null, Rep.class);
        System.out.println("get:"+getRep);

        // 2、傳送Post請求
        IdKey postBody = new IdKey(1,"id-key") ;
        Rep postRep = execute(BASE_URL+"/postApi", Method.POST.name(), headers, buildBody(postBody), Rep.class);
        System.out.println("post:"+postRep);

        // 3、傳送Put請求
        IdKey putBody = new IdKey(2,"key-id") ;
        Rep putRep = execute(BASE_URL+"/putApi", Method.PUT.name(), headers, buildBody(putBody), Rep.class);
        System.out.println("put:"+putRep);

        // 4、傳送Delete請求
        Rep delRep = execute(BASE_URL+"/delApi/2", Method.DELETE.name(), headers, null, Rep.class);
        System.out.println("del:"+delRep);
    }
    /**
     * 構建JSON請求體
     */
    public static RequestBody buildBody (Object body){
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        return RequestBody.create(mediaType, JSONUtil.toJsonStr(body)) ;
    }
    /**
     * 構建OkHttpClient物件
     */
    public static OkHttpClient buildOkHttp () {
        return new OkHttpClient.Builder()
                .readTimeout(10, TimeUnit.SECONDS).connectTimeout(6, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(15, 5, TimeUnit.SECONDS))
                .build();
    }
    /**
     * 執行請求
     */
    public static <T> T execute (String url, String method,
                                 Headers headers, RequestBody body,
                                 Class<T> repClass) {
        // 請求建立
        OkHttpClient httpClient = buildOkHttp() ;
        Request.Builder requestBuild = new Request.Builder()
                .url(url).method(method, body);
        if (headers != null) {
            requestBuild.headers(headers);
        }
        try  {
            // 請求執行
            Response response = httpClient.newCall(requestBuild.build()).execute();
            // 結果轉換
            InputStream inStream = null;
            if (response.isSuccessful()) {
                ResponseBody responseBody = response.body();
                if (responseBody != null) {
                    inStream = responseBody.byteStream();
                }
            }
            if (inStream != null) {
                try {
                    byte[] respByte = IoUtil.readBytes(inStream);
                    if (respByte != null) {
                        return JSONUtil.toBean(new String(respByte, Charset.defaultCharset()), repClass);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    IoUtil.close(inStream);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

4、RestTemplate

public class TestRestTemplate {

    private static final String BASE_URL = "http://localhost:8083" ;
    public static void main(String[] args) {

        RestTemplate restTemplate = buildRestTemplate() ;
        // 1、傳送Get請求
        Map<String,String> paramMap = new HashMap<>() ;
        Rep getRep = restTemplate.getForObject(BASE_URL+"/getApi/1",Rep.class,paramMap);
        System.out.println("get:"+getRep);

        // 2、傳送Post請求
        IdKey idKey = new IdKey(1,"id-key") ;
        Rep postRep = restTemplate.postForObject(BASE_URL+"/postApi",idKey,Rep.class);
        System.out.println("post:"+postRep);

        // 3、傳送Put請求
        IdKey idKey2 = new IdKey(2,"key-id") ;
        restTemplate.put(BASE_URL+"/putApi",idKey2,paramMap);

        // 4、傳送Delete請求
        restTemplate.delete(BASE_URL+"/delApi/2",paramMap);

        // 5、自定義Header請求
        HttpHeaders headers = new HttpHeaders();
        headers.add("Token","AdminSup");
        HttpEntity<IdKey> requestEntity = new HttpEntity<>(idKey, headers);
        ResponseEntity<Rep> respEntity = restTemplate.exchange(BASE_URL+"/postApi",
                                            HttpMethod.POST, requestEntity, Rep.class);
        System.out.println("post-header:"+respEntity.getBody());
    }

    private static RestTemplate buildRestTemplate (){
        // 1、引數配置
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(3000);
        factory.setConnectTimeout(6000);
        // 2、建立物件
        return new RestTemplate(factory) ;
    }
}

五、參考原始碼

程式設計文件:
https://gitee.com/cicadasmile/butte-java-note

應用倉庫:
https://gitee.com/cicadasmile/butte-flyer-parent