java网络编程概述及例题

网络编程概述

计算机网络

把分布在不同地理区域的计算机与专门的外部设备用通信线路连成一个规模大、功能强的网络系统,从而使众多的计算机可以方便地互相传递信息、共享硬件、软件、数据信息等资源。

网络编程的目的

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

网络编程中的两个主要问题

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

网络编程中的两个要素

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

网络通信协议

在这里插入图片描述

IP与端口号

什么是 IP ?

在这里插入图片描述

什么是端口号?

在这里插入图片描述

InetAddress类

在java中使用InetAddress类代表IP

域名: www.baidu.com
	域名-->DNS-->本机hosts-->网络服务器
	通过域名访问,先DNS解析,找本机hosts件中的地址是否存在,不存在,同各国网络服务器查找
本地回路地址:127.0.0.1 对应着:localhost
实例化InetAddress两个方法:getByName(String host),getLocalHost()
			 两个常用方法:getHostName(),getHostAddress()
public static void main(String[] args) {
        try {
            //获取一个InetAddress对象,InetAddress构造器私有化,故无法调用构造器。
            InetAddress inet1 = Inet4Address.getByName("192.168.233.2");
            System.out.println(inet1);//   /192.168.233.2

            InetAddress inet2 = InetAddress.getByName("www.baidu.com");
            System.out.println(inet2);//  www.baidu.com/61.135.169.125

            InetAddress inet3 = InetAddress.getByName("127.0.0.1");
            System.out.println(inet3);//  /127.0.0.1
            //获取本机IP
            InetAddress localHost = InetAddress.getLocalHost();
            System.out.println(localHost);// DESKTOP-K49TTDJ/192.168.146.1 局域网本地地址 与127.0.0.1一样

            //getHostName():获取域名
            System.out.println(inet2.getHostName());//www.baidu.com

            //getHostAddress():获取IP地址
            System.out.println(inet2.getHostAddress());// 61.135.169.125

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

TCP协议与UDP协议

区别

在这里插入图片描述

TCP三次握手,四次挥手

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

TCP实例1

/**
 * 实现TCP网络编程
 * 例子1:客户端发送信息给服务端,服务端将数据显示在控制台上
 * @author JIANGJINGWEI
 * @create 2020-05-09-13:49
 */
public class TCTest1 {
    //客户端
    @Test
    public void client()  {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1.创建Socket对象,指明服务器端的IP和端口号
            socket = new Socket(InetAddress.getByName("127.0.0.1"),888);
            //2.获取一个输出流,用于输出数据
            os = socket.getOutputStream();
            //3.写出数据操作
            os.write("你好世界!".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //4.资源关闭
                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,指明自己的端口号,IP是默认的主机IP
            ss = new ServerSocket(888);
            //2.调用accept()表示接收来自于客户端的socket
            socket = ss.accept();
            //3.获取输入流
            is = socket.getInputStream();
            //不建议可能会有乱码
//        byte[] buffer  = new byte[5];
//        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);//将数据写入到ByteArrayOutputStream的数组
            }
            System.out.println(baos.toString());
            System.out.println("收到了来自于"+socket.getInetAddress().getHostAddress()+"的数据");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5.资源关闭
            if(baos != null){
                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();
                }
            }
        }


    }
}

TCP实例2


/**
 * 实现TCP的网络编程
 * 例题2:客户端发送文件给服务器,服务端将文件保存在本地。
 * 异常需要用trycatch,此处简写
 * @author JIANGJINGWEI
 * @create 2020-05-09-14:20
 */
public class TCTest2 {
    @Test
    public void client() throws IOException {
        Socket socket = new Socket(InetAddress.getLocalHost(), 9090);
        OutputStream os = socket.getOutputStream();
        FileInputStream fis = new FileInputStream(new File("网络通信协议.png"));
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1){
            os.write(buffer,0,len);
        }
        fis.close();
        os.close();
        socket.close();
    }
    @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("网络通信协议1.png"));
        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();

    }
}

TCP实例3

/**
 * 实现TCP的网络编程
 * 例题3:从客户端发送文件给服务端,服务端保存到本地,并返回“发送成功”给客户端。
 * 异常处理应选用trycatch
 * @author JIANGJINGWEI
 * @create 2020-05-09-14:34
 */
public class TCTest3 {
    @Test
    public void client() throws IOException {
        Socket socket = new Socket(InetAddress.getLocalHost(), 9091);
        OutputStream os = socket.getOutputStream();
        FileInputStream fis = new FileInputStream(new File("网络通信协议.png"));
        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[] buffer1 = new byte[5];
        int len1;
        while((len1 = is.read(buffer)) != -1) {
            baos.write(buffer,0,len1);//将数据写入到ByteArrayOutputStream的数组
        }
        System.out.println(baos.toString());
        is.close();
        baos.close();
        fis.close();
        os.close();
        socket.close();
    }
    @Test
    public void server() throws IOException {
        ServerSocket ss = new ServerSocket(9091);

        Socket socket = ss.accept();

        InputStream is = socket.getInputStream();
        FileOutputStream fos = new FileOutputStream(new File("网络通信协议2.png"));
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }
        //服务器端给客户端的反馈
        OutputStream os = socket.getOutputStream();
        os.write("数据已收到".getBytes());
        os.close();
        fos.close();
        is.close();
        socket.close();
        ss.close();

    }
}

UDP实例

public class UDTest1 {
    //发送端
    @Test
    public void sender() throws IOException {
        
        DatagramSocket socket = new DatagramSocket();

        String str = "UDP发送数据";
        byte[] data = str.getBytes();
        InetAddress inet = InetAddress.getLocalHost();
        //将数据包装到packet里
        DatagramPacket Packet = new DatagramPacket(data,0,data.length,inet,9090);
        socket.send(Packet);

    }
    //接收端
    @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

什么是URL?

在这里插入图片描述

URL类常用方法

public class URLTest1 {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("https://www.bilibili.com/video/BV1Kb411W75N?p=629");
        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());//获取查询名

    }
}

URL实例tomcat数据下载

将tomcat服务器启动后运行一下代码

public class URLTest2 {
    public static void main(String[] args)  {
        HttpURLConnection urlConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            URL url = new  URL("https://localhost:8080/examples/aa.png");
            //获取连接对象
            urlConnection = (HttpURLConnection) url.openConnection();
            //获取连接
            urlConnection.connect();
            is = urlConnection.getInputStream();
            fos = new FileOutputStream( "day01\\aaa.png");
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null){

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

                try {
                    is.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、付费专栏及课程。

余额充值