网络编程

五、网络编程概述

5.1 实现网络通信,待解决的问题

*   1. 如何准确地定位网络上一台或多台主机;定位主机上的特定的应用
*   2. 找到主机后如何可靠高效地进行数据传输

5.2 如何解决上述问题

网络通信的两大要素:
*   要素一:IP 和 端口号。 解决问题1
*   要素二:网路通信协议。 解决问题2

5.3 要素一和要素二的概述:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3Bp5SznI-1620890281451)(day27笔记.assets/1584762649499.png)]

其中,TCP/IP协议模型成为事实上的标准。

六、IP和端口号

6.1 IP

 * 1. IP:唯一的标识 Internet 上的计算机(通信实体)
 * 2. IP分类:  角度一: ipv4  和  ipv6
 *              角度二: 公网地址   和  私有地址:192.168.0.0 - 192.168.255.255
 *
 * 3. 可以使用一个域名来代表一个具体的ip地址。
 *      比如: www.atguigu.com    www.baidu.com   www.vip.com  www.jd.com   www.mi.com
 * 4. 本地的ip:127.0.0.1  本地回路地址。 别名:localhost
 * 5. 代码中使用InetAddress类的一个对象表示一个具体的ip地址
 *      如何实例化InetAddress:getByName(String host)可以输入域名,也可以输入IP地址
 *                            getLocalHost()
 *      两个常用方法:getHostName();获取本机域名
 * 					 getHostAddress();获取本机地址
public class IPtest3 {
    @Test
    public void test(){
        try {
            InetAddress ine=InetAddress.getByName("www.atguigu.com");
            System.out.println(ine.getHostAddress());
            //61.184.215.185
           System.out.println(ine.getHostName());
           //www.atguigu.com
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

代码实现:

public class InetAddressTest {

    public static void main(String[] args) {
        try {
            InetAddress inetAddress = InetAddress.getByName("192.168.23.43");

            InetAddress inetAddress1 = InetAddress.getByName("www.atguigu.com");
            System.out.println(inetAddress1);//www.atguigu.com/124.200.113.114

            InetAddress localHost = InetAddress.getLocalHost();
            System.out.println(localHost);

            //测试方法:
            System.out.println(inetAddress1.getHostName());
            System.out.println(inetAddress1.getHostAddress());

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

    }

}

6.2 端口号

1. 端口号标识正在计算机上运行的进程(程序)
	不同的进程有不同的端口号

2. 被规定为一个 16 位的整数 0~65535。

3. 端口分类:
>公认端口:0~1023。被预先定义的服务通信占用(如:HTTP占用端口80,FTP占用端口21,Telnet占用端口23)
>注册端口:1024~49151。分配给用户进程或应用程序。(如:Tomcat占用端口8080,MySQL占用端口3306,Oracle占用端口1521等)。
> 动态/私有端口:49152~65535。

4. 端口号与IP地址的组合得出一个网络套接字:Socket。

七、TCP和UDP编程

7.1 概述

在这里插入图片描述
在这里插入图片描述

注:当数据传输完成后需要挥手,服务端与客户端都可以主动挥手,一般客户端挥手,服务端24h都开着

7.2TCP网络编程

运行方式:先打开服务端,再打开客户端
例题1:

import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class IPtest {
    @Test
    public void client() {//客户端
        Socket socket = null;
        OutputStream os = null;
        try {
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");//指明对方的ip
            int port = 9090;//指明对方的端口号
            //1. 创建Socket的实例
            socket = new Socket(inetAddress, port);

            //2.获取一个输出流
            os = socket.getOutputStream();
            //3. 写出数据
            os.write("你好,我是客户端,多多关照".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. 关闭资源
            try {
                if (os != null)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null)
                    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
            int port = 9090;
            ss = new ServerSocket(port);
            //2. 接收来自于客户端的Socket
            socket = ss.accept();
            //3. 获取输入流
            is = socket.getInputStream();

            System.out.println("收到了来自于" + socket.getInetAddress().getHostAddress() + "的数据:");

            //4. 读取数据
            byte[] buffer = new byte[1024];
            baos = new ByteArrayOutputStream();
            int len;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5. 关闭资源
            try {
                if (baos != null)
                    baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //服务端的socket也可以关闭,但是一般服务器是开启的。
            try {
                if (ss != null)
                    ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

  • 例题2
package com.atguigu.java1;

import com.sun.deploy.trace.SocketTraceListener;
import org.junit.Test;

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

/**
 *  2.客户端发送文件给服务端,服务端将文件保存在本地。
 *
 *
 * @author shkstart
 * @create 2020 下午 2:43
 */
public class TCPTest1 {

    //仍然应该使用try-catch-finally处理异常
    @Test
    public void client() throws IOException {
        //1.
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 8989);
        //2.
        FileInputStream fis = new FileInputStream("baby.jpg");
        OutputStream os = socket.getOutputStream();
        //3.
        byte[] buffer = new byte[1024];
        int len;
        while((len = fis.read(buffer)) != -1){
            os.write(buffer,0,len);
        }
        //4.
        os.close();
        fis.close();
        socket.close();
    }

    //仍然应该使用try-catch-finally处理异常
    @Test
    public void server() throws IOException {
        //1.
        ServerSocket serverSocket = new ServerSocket(8989);
        //2.
        Socket socket = serverSocket.accept();
        //3.
        InputStream is = socket.getInputStream();
        FileOutputStream fos = new FileOutputStream("src/baby123.jpg");
        //4.
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }
        //5.
        fos.close();
        is.close();
        socket.close();
        //serverSocket.close();
    }
}

  • 例题3
package com.atguigu.java1;

import org.junit.Test;

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

/**
 * 3.从客户端发送文件给服务端,服务端保存到本地。并返回“发送成功”给客户端。并关闭相应的连接。
 * @author shkstart
 * @create 2020 下午 2:44
 */
public class TCPTest2 {
    //仍然应该使用try-catch-finally处理异常
    @Test
    public void client() throws IOException {
        //1.
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 8989);
        //2.
        FileInputStream fis = new FileInputStream("baby.jpg");
        OutputStream os = socket.getOutputStream();
        //3.
        byte[] buffer = new byte[1024];
        int len;
        //read是个阻塞式的方法
        while((len = fis.read(buffer)) != -1){
            os.write(buffer,0,len);
        }
        System.out.println("client-------1");
        //显式的关闭输出流
        socket.shutdownOutput();
		//强制关闭客户端,不然还在等待客户端继续发送
        //接收来自于服务器端的数据,并显示
        InputStream is = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] newBuf = new byte[10];
        int newLen;
        while((newLen = is.read(newBuf)) != -1){
            baos.write(newBuf,0,newLen);
        }
        System.out.println(baos.toString());

        //4.
        is.close();
        baos.close();
        os.close();
        fis.close();
        socket.close();
    }

    //仍然应该使用try-catch-finally处理异常
    @Test
    public void server() throws IOException {
        //1.
        ServerSocket serverSocket = new ServerSocket(8989);
        //2.
        Socket socket = serverSocket.accept();
        //3.
        InputStream is = socket.getInputStream();
        FileOutputStream fos = new FileOutputStream("src/babyabc.jpg");
        //4.
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }
        System.out.println("server-------1");
        //服务器给客户端反馈数据
        OutputStream os = socket.getOutputStream();
        os.write("收到你的靓照,非常的漂亮!".getBytes());

        //5.
        os.close();
        fos.close();
        is.close();
        socket.close();
        //serverSocket.close();
    }
}

八、URL编程

8.1 介绍

1. URL(Uniform Resource Locator):统一资源定位符,它表示 Internet 上某一资源的地址。

2. 使用URL类表示互联网的某一资源
http://localhost:8080/examples/playgirl.jpg?keyword=girl
协议名   主机名    端口号    资源地址            请求数据
3. 实例化
4. 主要方法

8.2 测试

try {
     URL url = new URL("http://localhost:8080/examples/playgirl.jpg?keyword=girl");

//            public String getProtocol(  )     获取该URL的协议名
//            public String getHost(  )           获取该URL的主机名
//            public String getPort(  )            获取该URL的端口号
//            public String getPath(  )           获取该URL的文件路径
//            public String getFile(  )             获取该URL的文件名
//            public String getQuery(   )        获取该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.getFile());
            System.out.println(url.getQuery());

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

        }

8.3 下载数据

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/playgirl.jpg");

            urlConnection = (HttpURLConnection) url.openConnection();

            is = urlConnection.getInputStream();
            fos = new FileOutputStream("playgirl.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 {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (urlConnection != null)
                urlConnection.disconnect();
        }


    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值