IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> Java基础—网络编程 -> 正文阅读

[网络协议]Java基础—网络编程

一、网络编程概述

1、网络编程的目的:

直接或间接地通过网络协议与其它计算机实现数据交换,进行通讯。

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

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

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

二、网络通信要素概述

网络编程中的两个要素:

①对应问题一:IP和端口号

②对应问题二:提供网络通信协议:

TCP/IP参考模型(应用层、传输层、网络层、物理+数据链路层)

三、通信要素1: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 www.vip.com

5、本地回路地址:127.0.0.1 对应着:localhost

6、如何实例化InetAddress:getByName(String host) / getLocalHost()

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

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

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

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

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

public class InetAddressTest {

    public static void main(String[] args) {

        try {
            InetAddress inet1 = InetAddress.getByName("192.168.10.14");
            System.out.println(inet1);

            InetAddress inet2 = InetAddress.getByName("www.atguigu.com");
            System.out.println(inet2);

            InetAddress inet3 = InetAddress.getByName("127.0.0.1");
            System.out.println(inet3);

            //获取本地ip
            InetAddress inet4 = InetAddress.getLocalHost();
            System.out.println(inet4);

            //getHostName()
            System.out.println(inet2.getHostName());
            //getHostAddress()
            System.out.println(inet2.getHostAddress());

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

四、通信要素2:网络协议

1、TCP协议:

> 使用TCP协议前,须先建立TCP连接,形成传输数据通道

> 传输前,采用"三次握手"方式,点对点通信,是可靠的

> TCP协议进行通信的两个应用进程:客户端、服务端

> 在连接中可进行大数据量的传输

> 传输完毕,需释放已建立的连接,效率低

2、UDP协议

> 将数据、源、目的封装成数据包,不需要建立连接

> 每个数据报的大小限制在64K内

> 发送不管对方是否准备好,接收方收到也不确认,故是不可靠的

> 可以广播发送

> 发送数据结束时无需释放资源,开销小,速度快

3、Socket

Socket类的常用构造器:

public Socket(InetAddress address,int port):创建一个流套接字并将其连接到指定IP地址的指定端口号。

public Socket(String host,int port):创建一个流套接字并将其连接到指定主机上的指定端口号。

Socket类的常用方法:

public InputStream getInputStream():返回此套接字的输入流。可以用于接收网络消息

public OutputStream getOutputStream():返回此套接字的输出流。可以用于发送网络消息

public InetAddress getInetAddress():此套接字连接到的远程IP地址;如果套接字是未连接的,则返回null

public InetAddress getLocalAddress():获取套接字绑定的本地地址。即本端的IP地址

public int getPort():此套接字连接到的远程端口号;如果尚未连接套接字,则返回0

public int getLocalPort():返回此套接字绑定到的本地端口。如果尚未绑定套接字,则返回-1。即本端的端口号。

public void close():关闭此套接字。套接字关闭后,便不可在以后的网络连接中使用(即无法重新连接或重新绑定)。需要创建新的套接字对象。关闭此套接字也将会关闭该套接字的InputStream和OutputStream。

public void shutdownInput():如果在套接字上调用shutdownInput()后,从套接字输入流读取内容,则流将返回EOF(文件结束符)。即不能在从此套接字的输入流中接收任何数据。

public void shutdownOutput():禁用此套接字的输出流。对于TCP套接字,任何以前写入的数据都将被发送。并且后跟TCP的正常连接终止序列。如果在套接字上调用shutdownOutput()后写入套接字输出流,则该流将抛出IOException。即不能通过此套接字的输出流发送任何数据。

五、TCP网络编程

eg1:客户端发送信息给服务端,服务端将数据显示在控制台上。

    //客户端
    @Test
    public void client()  {
        
        Socket socket = null;
        OutputStream os = null;
        try {
            //1.创建Socket对象,指明服务器端的ip和端口号
            InetAddress inet = InetAddress.getByName("192.168.14.100");
            socket = new Socket(inet,8899);
            //2.获取一个输出流,用于输出数据
            os = socket.getOutputStream();
            //3.写出数据的操作
            os.write("你好,我是客户端mm".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源的关闭
            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(8899);
            //2.调用accept()表示接收来自于客户端的socket
            socket = ss.accept();
            //3.获取输入流
            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.print(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(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ss != null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

eg2:客户端发送文件给服务器,服务器将文件保存在本地。

    //这里涉及到的异常,应该使用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("beauty.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();

        InputStream is = socket.getInputStream();

        FileOutputStream fos = new FileOutputStream(new File("beauty1.jpg"));

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

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

    }

eg3:从客户端发送文件给服务器,服务器保存到本地。并返回"发送成功"给客户端。

    //这里涉及到的异常,应该使用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("beauty.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[] buffer = new byte[20];
        int len1;
        while((len1 = is.read(buffer)) != -1){
            baos.write(buffer,0,len);
        }

        System.out.println(baos.toString());

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

    }

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

        Socket socket = ss.accept();

        InputStream is = socket.getInputStream();

        FileOutputStream fos = new FileOutputStream(new File("beauty2.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网络编程

    //这里涉及到的异常,应该使用try-catch-finally处理
    //发送端
    @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();

    }

    //这里涉及到的异常,应该使用try-catch-finally处理
    //接收端
    @Test
    public void receiver() 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、格式:

http://localhost:8080/examples/beauty.jpg?username=Tom

协议? 主机名? 端口号? 资源地址? ? ? ? ?参数列表

3、常用方法

public String getProtocol():获取该URL的协议名

public String getHost():获取该URL的主机名

public String getPort():获取该URL的端口号

public String getPath():获取该URL的文件路径

public String getFile():获取该URL的文件名

public String getQuery():获取该URL的查询名

public class URLTest {

    public static void main(String[] args) {

        try {

            URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");

//            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();
            }
        }

    }
}
  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2022-02-14 21:34:12  更:2022-02-14 21:36:20 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年10日历 -2024/10/5 11:26:53-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码