Android网络学习

330 阅读5分钟

目标: 熟悉整个网络分层、可以看懂公司的网络代码、可以理解数据的传输

async   英  [əˈsɪŋk]  美  [əˈsɪŋk]

  • abbr. 异步,非同步(asynchronous)

学习思路:先学习概括性的内容,达到可以理解,可以达到上方的学习目标即可。后续再学习系统的知识点。

adb

资料:

深入学习资料:

问题:

  • 心跳包
  • socket链接 看java基础的书
  • socket是什么?

路由器在osi第五层,网络层 ssh

  • MAC地址
    • 大家在发数据时,会把目标的MAC地址放在数据的开头,每台计算机都监听电线的信号,发现MAC地址是自己就接收数据,以此实现2台计算机之间的联通

涉及到的知识点

可以给每个知识点都写一篇文章,相似的可以写在一起

  • 计算机退避机制
  • 交换机: 可以实现2个网络的沟通访问
  • 路由器: 可以实现多个网络的沟通访问
  • WAN 广域网 Wide Area Network
  • LAN 局域网
  • ISP 互联网服务提供商; 网络服务提供商; 因特网服务提供商; 互联网服务供应商; 网络服务提供者
  • 互联网是一个巨型分布式网络,数据会沿着互联网主干传输到制定位置的计算机
  • IP地址 192.168.1.3
  • 域名 www.google.com
    • 之所以写域名,是因为网络供应商考虑我们记不住,给我们添加了一个付费服务:DNS域名解析
  • DNS 全称Domain Name System,Domain Name被译为域名,中文名为域名系统,也称为域名解析系统;另外域名服务器Domain Name Server也简称为DNS。域名系统是因特网的一项内核服务,它作为可以将域名和IP地址相互映射的一个分布式数据库,能够使人更方便的访问互联网
    • 我们上网时,写完域名之后,浏览器先去连接DNS服务器,DNS服务器查找这个域名对应的IP地址返回给我们,浏览器再根据这个IP地址访问网站。注意,我们使用域名访问时,第一步是先通过dns服务器拿到ip地址,我们是可以获取到真实要访问的ip地址的。
  • 域名分级
    • 顶级域名: .com/.cn/.gov 这些就是
    • 二级域名 google 这些就是
    • 子域名 images 就是
  • 三次握手

协议

就好比我们发快递,总要按贴一张快递单,快递单也必须按照制定规矩来写一样。数据在网络之间传递,必须遵循互联网的规定,这种用于传输数据的规定加做:协议

  • IP协议,这是最早的协议,负责把数据包送到正确的计算机
  • UDP协议,只管发送的协议,负责把数据包送到正确的程序
  • TCP协议,带重发,可以知道数据是否到达的协议,负责把数据包送到正确的程序

TCP 协议

TCP 协议被认为是稳定的协议,HTTP 协议就是基于 TCP 协议实现的,有以下特点

  • 面向连接,三次握手,四次挥手
  • 双向通信,可以同时发送,接收数据
  • 保证数据可以按序发送,按序到达
  • 超时重传

网络7层结构

image.png

mac地址是唯一的吗?
每块网卡的MAC地址都是唯一的,其实不光是网卡有MAC地址,很多网络设备也都有自己的MAC地址,而且有的还不止一个。比如路由器上有很多的端口,每个端口都有一个自己专属的MAC地址。所有的MAC地址都是唯一、不能重复的

五层协议介绍

常用的为五层结构: 想象一搜撒网的传:应用层、传输层、网络层、数据链路层、物理层

什么是Socket?

参考什么是Socket?

一、什么是Socket?

在计算机通信领域,socket 被翻译为“套接字”(套接字=主机+端口号),它是计算机之间进行通信的一种约定或一种方式。通过 socket这种约定,一台计算机可以接收其他计算机的数据,也可以向其他计算机发送数据 socket起源于Unix,而Unix/Linux基本哲学之一就是“一切皆文件”,都可以用“打开open –> 读写write/read关闭close”模式来操作。 我的理解就是Socket就是该模式的一个实现,它只是提供了一个针对TCP或者UDP编程的接口:即socket是一种特殊的文件,一些socket函数就是对其进行的操作(读/写IO、打开、关闭)。

image.png

二、socket通信流程

image.png

三、socket 示例(python3)

server.py

# -*- coding: utf-8 -*-

#==============================================================================
# 1. TCP server端代码
# #!/usr/bin/env python
# #
# # -*- coding:utf-8 -*-
# #
#==============================================================================

from socket import *
from time import ctime

HOST = ''
PORT = 21568
BUFSIZE=1024
ADDR=(HOST, PORT)

tcpSrvSock=socket(AF_INET, SOCK_STREAM)
tcpSrvSock.bind(ADDR)
tcpSrvSock.listen(5)
while True:
    print ('waiting for connection ...',ctime())
    tcpCliSock,addr = tcpSrvSock.accept()
    print ('... connected from:', addr)
    while True:
        data=tcpCliSock.recv(BUFSIZE)
        print("receive from 2:",data)
        if not data:
            break
        tcpCliSock.send(str.encode('[%s] %s'%(ctime(), data)))
        print ([ctime()],':',data)

    
    tcpCliSock.close()
tcpSrvSock.close()

client.py

# -*- coding: utf-8 -*-

#==============================================================================
# 2. TCP client端代码
# #!/usr/bin/env python
# #
# # -*- coding:utf-8 -*-
# #
#==============================================================================

from socket import *

HOST='localhost'
PORT=21567
BUFSIZE=1024
ADDR=(HOST, PORT)

tcpCliSock=socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)

while True:
    data = input('>')
    print(type(data))
    data = str.encode(data)
    print(data)
    if not data:
        break
    tcpCliSock.send(data)
    data=tcpCliSock.recv(BUFSIZE)
    if not data:
        break
    print (data)

tcpCliSock.close()

image.png
————————————————
版权声明:本文为CSDN博主「大数据老司机」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:blog.csdn.net/qq_35745940…

DNS

Android中查找DNS的类,可以从OkHttpClient类中的dns对应的Dns类看起
目标:可以学习c语言之后,看下Android底层源码 blog.csdn.net/b178903294/…

public interface Dns {
  /**
   * A DNS that uses {@link InetAddress#getAllByName} to ask the underlying operating system to
   * lookup IP addresses. Most custom {@link Dns} implementations should delegate to this instance.
   */
  Dns SYSTEM = new Dns() {
    @Override public List<InetAddress> lookup(String hostname) throws UnknownHostException {
      if (hostname == null) throw new UnknownHostException("hostname == null");
      try {
        return Arrays.asList(InetAddress.getAllByName(hostname));
      } catch (NullPointerException e) {
        UnknownHostException unknownHostException =
            new UnknownHostException("Broken system behaviour for dns lookup of " + hostname);
        unknownHostException.initCause(e);
        throw unknownHostException;
      }
    }
  };

  /**
   * Returns the IP addresses of {@code hostname}, in the order they will be attempted by OkHttp. If
   * a connection to an address fails, OkHttp will retry the connection with the next address until
   * either a connection is made, the set of IP addresses is exhausted, or a limit is exceeded.
   */
  List<InetAddress> lookup(String hostname) throws UnknownHostException;
}

关键方法InetAddress.getAllByName(hostname),来到InetAddress类


static final InetAddressImpl impl = new Inet6AddressImpl();

public static InetAddress[] getAllByName(String host)
    throws UnknownHostException {
    // Android-changed: Resolves a hostname using Libcore.os.
    // Also, returns both the Inet4 and Inet6 loopback for null/empty host
    return impl.lookupAllHostAddr(host, NETID_UNSET).clone();
}

继续来到Inet6AddressImpl类,libcore.net.InetAddressUtils

import libcore.net.InetAddressUtils;

@Override
public InetAddress[] lookupAllHostAddr(String host, int netId) throws UnknownHostException {
    if (host == null || host.isEmpty()) {
        // Android-changed: Return both the Inet4 and Inet6 loopback addresses
        // when host == null or empty.
        return loopbackAddresses();
    }

    // Is it a numeric address?
    InetAddress result = InetAddressUtils.parseNumericAddressNoThrowStripOptionalBrackets(host);
    if (result != null) {
        return new InetAddress[] { result };
    }

    return lookupHostByName(host, netId);
}