一、网络编程中有两个主要的问题:

1.如何准确地定位网络上一台或多台主机;定位主机上的特定的应用

2.找到主机后如何可靠高效地进行数据传输

二、网络编程中的两个要素:

1.对应问题一:IP和端口号

2.对应问题二:提供网络通信协议:TCP/IP参考模型(应用层、传输层、网络层、物理+数据链路层)

三、通信要素一:IP和端口号

  1. IP:唯一的标识 Internet 上的计算机(通信实体)
  2. 在Java中使用InetAddress类代表IP
  3. IP分类:IPv4 和 IPv6 ; 万维网 和 局域网
  4. 域名: www.baidu.com www.mi.com www.sina.com www.jd.com
  5. 本地回路地址(本机地址):127.0.0.1 对应着:localhost
  6. 如何实例化InetAddress:两个方法:getByName(String host) 、 getLocalHost()

两个常用方法:getHostName() / getHostAddress()

  1. 端口号:正在计算机上运行的进程。

要求:不同的进程有不同的端口号

范围:被规定为一个 16 位的整数 0~65535。

  1. 端口号与IP地址的组合得出一个网络套接字:Socket
  1. public class InetAddressTest {
  2. public static void main(String[] args) {
  3. try {
  4. InetAddress inet1=InetAddress.getByName("127.0.0.1");
  5. System.out.println(inet1);
  6. InetAddress inet2=InetAddress.getByName("www.bilibili.com");
  7. System.out.println(inet2);
  8. //获取本机地址
  9. InetAddress inet3=InetAddress.getLocalHost();
  10. System.out.println(inet3);
  11. } catch (UnknownHostException e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. }

实现TCP网络编程

例子一:

客户端发送信息给服务端,服务端将数据显示在控制台上。
public class TCPTest1 {
    //客户端
    @Test
    public void client() {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1.创建socket对象指明服务器端ip和端口号
            InetAddress inet = InetAddress.getByName("192.168.0.107");
            socket = new Socket(inet, 8989);
            //2.获取一个输出流,用于输出数据
            os = socket.getOutputStream();
            os.write("你好我是客户端".getBytes());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException 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();
                }
            }
        }
    }
    //服务端
    @Test
    public void server(){
        ServerSocket ss=null;
        Socket socket=null;

        InputStream is=null;
        ByteArrayOutputStream baos=null;

        try {
            //1.创建服务端的serverSocket,指明端口号
            ss=new ServerSocket(8989);
            //2.调用accept()表示接受来自于客户端socket
            socket=ss.accept(); 

            //获取输入流
            is=socket.getInputStream();
            //不建议这样写可能会出现乱码
/*            byte [] buffer=new byte[1024];
            int len;
            while ((len=is.read(buffer)) !=-1){
                String str=new String(buffer,0,len);
                System.out.println(str);
            }*/
            //4.读取输入流中的数据
            baos=new ByteArrayOutputStream();
            byte [] buffer=new byte[5];
            int len;
            while ((len=is.read(buffer)) !=-1){
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());
            System.out.println("收到了来自于:"+socket.getInetAddress().getHostAddress()+"的数据");

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源

            if (baos !=null){
                //5.关闭资源
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (is !=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ss !=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

实现TCP的网络编程

例题2:客户端发送文件给服务端,服务端将文件保存在本地。
public class TCPTest2 {

        /*
    这里涉及到的异常,应该使用try-catch-finally处理
     */
    //下面是为了更的测试
    @Test
    public void client() throws IOException {
        Socket socket=new Socket(InetAddress.getByName("127.0.0.1"),9090);
        OutputStream os=socket.getOutputStream();
        FileInputStream fis = new FileInputStream(new File("手机.jpg"));


        byte [] buffer =new byte[1024];
        int len;
        while ((len= fis.read(buffer)) !=-1){
            os.write(buffer,0,len);
        }

        fis.close();
        os.close();
        socket.close();
    }

            /*
    这里涉及到的异常,应该使用try-catch-finally处理
     */
    //下面是为了更的测试
    @Test
    public void server() throws IOException {
        ServerSocket ss=new ServerSocket(9090);

        Socket socket=ss.accept(); //表示可以接收客戶端传来的socket

        InputStream is=socket.getInputStream();

        FileOutputStream fos=new FileOutputStream(new File("手机2.jpg"));

        byte[] buffer=new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
            fos.write(buffer,0,len);

        }
        fos.close();
        is.close();
        ss.close();
    }
}

例题3:从客户端发送文件给服务端,服务端保存到本地。并返回“发送成功”给客户端。

并关闭相应的连接。

public class TCPTest3 {

    /*
        这里涉及到的异常,应该使用try-catch-finally处理
         */

    @Test
    public void client() throws IOException {
        Socket socket=new Socket(InetAddress.getByName("127.0.0.1"),9090);

        OutputStream os=socket.getOutputStream();

        FileInputStream fis=new FileInputStream(new File("行李箱.jpg"));

        byte [] buffer=new byte[1024];

        int len;
        while ((len=fis.read(buffer)) !=-1){

            os.write(buffer,0,len);
        }

        //关闭数据输出
        socket.shutdownOutput();

        //接受来自服务端的数据,并显示到控制台上
        InputStream is=socket.getInputStream();
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        byte [] buffeer =new byte[1024];

        int len1;

        while ((len1=is.read(buffeer)) !=-1){
            baos.write(buffeer,0,len1);
        }
        System.out.println(baos.toString());
        fis.close();
        os.close();
        socket.close();
        baos.close();
    }

    @Test
    public void server() throws Exception{
        ServerSocket ss=new ServerSocket(9090);
        //获取客户端传过来的socket
        Socket socket=ss.accept();
        InputStream is = socket.getInputStream();
        FileOutputStream fos=new FileOutputStream(new File("行李箱2.jpg"));

        byte [] buffer=new byte[1024];
        int len;
        while ((len=is.read(buffer)) !=-1){
            fos.write(buffer,0,len);
        }
        System.out.println("图片传输完成!");

        //服务器给予客户端反馈
        OutputStream os=socket.getOutputStream();
        os.write("你好,图片已经收到了".getBytes());

        fos.close();
        is.close();
        socket.close();
        ss.close();
        os.close();
    }
}

UDP协议的详细解析

UDP数据报

一、UDP的概述(User Datagram Protocol,用户数据报协议)
UDP是传输层的协议,功能即为在IP的数据报服务之上增加了最基本的服务:复用和分用以及差错检测。

UDP无连接,时间上不存在建立连接需要的时延。空间上,TCP需要在端系统中维护连接状态,需要一定的开销。此连接装入包括接收和发送缓存,拥塞控制参数和序号与确认号的参数。UCP不维护连接状态,也不跟踪这些参数,开销小。空间和时间上都具有优势。
举个例子:

DNS如果运行在TCP之上而不是UDP,那么DNS的速度将会慢很多。
HTTP使用TCP而不是UDP,是因为对于基于文本数据的Web网页来说,可靠性很重要。
同一种专用应用服务器在支持UDP时,一定能支持更多的活动客户机。

分组首部开销小**,TCP首部20字节,UDP首部8字节。

UDP没有拥塞控制,应用层能够更好的控制要发送的数据和发送时间,网络中的拥塞控制也不会影响主机的发送速率。某些实时应用要求以稳定的速度发送,能容 忍一些数据的丢失,但是不能允许有较大的时延(比如实时视频,直播等)

UDP提供尽最大努力的交付,不保证可靠交付。所有维护传输可靠性的工作需要用户在应用层来完成。没有TCP的确认机制、重传机制。如果因为网络原因没有传送到对端,UDP也不会给应用层返回错误信息

UDP是面向报文的,对应用层交下来的报文,添加首部后直接乡下交付为IP层,既不合并,也不拆分,保留这些报文的边界。对IP层交上来UDP用户数据报,在去除首部后就原封不动地交付给上层应用进程,报文不可分割,是UDP数据报处理的最小单位。
正是因为这样,UDP显得不够灵活,不能控制读写数据的次数和数量。比如我们要发送100个字节的报文,我们调用一次sendto函数就会发送100字节,对端也需要用recvfrom函数一次性接收100字节,不能使用循环每次获取10个字节,获取十次这样的做法。

UDP常用一次性传输比较少量数据的网络应用,如DNS,SNMP等,因为对于这些应用,若是采用TCP,为连接的创建,维护和拆除带来不小的开销。UDP也常用于多媒体应用(如IP电话,实时视频会议,流媒体等)数据的可靠传输对他们而言并不重要,TCP的拥塞控制会使他们有较大的延迟,也是不可容忍的

public class UDPTest {

    @Test
    public void sender() throws IOException {

        DatagramSocket socket=new DatagramSocket();

        String str="以UDP方式进行发送!";
        byte [] data=str.getBytes();
        InetAddress inet=InetAddress.getLocalHost();
        DatagramPacket packet=new DatagramPacket(data,0,data.length,inet,9090);

        socket.send(packet);//发送数据包
        socket.close();

    }

    @Test
    public void reveiver() throws IOException {
        DatagramSocket socket =new DatagramSocket(9090);

        byte [] buffer=new byte[100];
        DatagramPacket packet =new DatagramPacket(buffer,0,buffer.length);
        socket.receive(packet);

        System.out.println(new String(packet.getData(),0,packet.getLength()));

        socket.close();
    }
}

URL网络编程:

1.URL:统一资源定位符,对应着互联网的某一资源地址

2.格式:

public class URLTest {

    public static void main(String[] args) {

        try {

            URL url = new URL("https://blog.csdn.net/tanga842428/article/details/52716875");

//            public String getProtocol(  )     获取该URL的协议名
            System.out.println(url.getProtocol());
//            public String getHost(  )           获取该URL的主机名
            System.out.println(url.getHost());
//            public String getPort(  )            获取该URL的端口号
            System.out.println(url.getPort());
//            public String getPath(  )           获取该URL的文件路径
            System.out.println(url.getPath());
//            public String getFile(  )             获取该URL的文件名
            System.out.println(url.getFile());
//            public String getQuery(   )        获取该URL的查询名
            System.out.println(url.getQuery());




        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

    }
}
 */
public class URLTest1 {

    public static void main(String[] args) {

        HttpURLConnection urlConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            URL url = new URL("http://localhost:8080/examples/beauty.jpg");

            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.connect();

            is = urlConnection.getInputStream();
            fos = new FileOutputStream("day10\\beauty3.jpg");

            byte[] buffer = new byte[1024];
            int len;
            while((len = is.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }

            System.out.println("下载完成");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(urlConnection != null){
                urlConnection.disconnect();
            }
        }
    }
}