java网络编程

2022/2/21 22:56:19

本文主要是介绍java网络编程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

* 一、网络编程中有两个主要的问题:
* 1.如何准确地定位网络上地一台或多态主机(IP);定位主机上地特定应用(端口号)
* 2.找到主机后如何可靠高效地进行网络传输
*
* 二、网络编程中的两个要素:
* 1.对应问题一:IP和端口号
* 2.对应问题二:提供网络通信协议:TCP/IP参考模型(应用层、传输层、网络层、物理+数据链路层)
*
*
* 三、通信要素:Ip和端口号
* 1.IP:唯一标识Internet上的计算机(通信实体)
* 2.在java中使用InetAddress类代表IP
* 3.Ip分类:IpV4和Ipv6:万维网和局域网
* 4.域名:www.baidu.com  www.bilibili.com  因为ip地址不容易记忆
* 域名可以是我们不用去记忆复杂的IP地址
* 在搜索引擎上面输入域名如:www.baidu.com   此时就会送到DNS(域名解析器) 然后解析出Ip地址
*
*
* 我们在hosts写域名 和IP地址也是同样的道理  如果输入这个域名  则指向固定的ip地址
*
* 5.本地回路地址:127.0.0.1对应着localhost
*
* 6.如何实例化InetAddress:两个方法:getByName(String host)、getLocalHost()
*
* 7.端口号标识正在计算机上运行的进程(程序)
*   不同的进程有不同的端口号
*   被规定为一个16位的整数0~65535
*   端口号分类:
*     公认端口号:0~1023.http-80 FTP-21 Telnet-23
*     注册端口号:1024~49151分配给用户进程或应用程序,如Tomcat-8080 mysql-3306 oracle-1521
*     动态/私有端口号:49152~65535
* 端口号与Ip地址组合得出一个网络套接字:Socket 网络编程的核心

1.InetAdress实例化:

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.bilibili.com");
            System.out.println(inet2);

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

            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.TCP网络编程:

* TCP协议:
*   使用TCP协议前,须先建立TCP连接,形成传输数据通道
*   传输前,采用“三次握手”方式,点对点通信,是可靠的
*   TCP协议进行通信的两个应用进程:客户端、服务端
*   在连接中可进行大量的数据传输
*   传输完毕,需释放已建立的连接、效率低 (四次挥手)
* 比如:打电话
//实现TCP的网络编程
//举例一:客户端发送信息给服务端,服务端将数据显示在控制台上
    //客户端
    @Test
    public void client(){
        Socket socket= null;
        OutputStream os = null;
        try {
            //创建Socket对象,指明服务器端的IP和端口号
            InetAddress inet=InetAddress.getByName("127.0.0.1");
            socket = new Socket(inet,8899);
            //获取一个输入流,用于输出数据
            os = socket.getOutputStream();
            //写入数据的操作
            os.write("你好  我是本机的客户端".getBytes());
        } 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(){

        Socket socket= null;
        InputStream is = null;
        ByteArrayOutputStream baos=null;
        try {
            //1.创建服务器端的ServerSocket,指明自己的端口号
            ServerSocket ss=new ServerSocket(8899);
            //2.调用accept()表示接收来自于客户端的socket
            socket = ss.accept();
            //3.获取输入流
            is = socket.getInputStream();
            //可能会出现乱码
//            byte[] cbuf=new byte[1024];
//            int len;
//            while((len=is.read(cbuf))!=-1){
//                String str=new String(cbuf,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 {
            //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();
                }
            }
        }


    }

例子二:实现客户端传给服务器一张照片 服务器收到照片后保存到本地并返回信息给客户端

@Test
    public void client(){
        Socket socket= null;
        OutputStream os = null;
        FileInputStream fis= null;
        InputStream is = null;
        ByteArrayOutputStream baos= null;
        try {
            //1.指明ip地址
            InetAddress inet=InetAddress.getByName("127.0.0.1");
            //2.提供ip和端口号  确定一个套接字socket
            socket = new Socket(inet,8890);
            //3.获取输入流,用于输出数据
            os = socket.getOutputStream();
            //4.文件对象实例化
            File file=new File("向涵之.jpg");
            //5.流的实例化
            fis = new FileInputStream(file);
            //6.将数据传输进去
            byte[] cbuf=new byte[1024];
            int len;
            while((len=fis.read(cbuf))!=-1){
                os.write(cbuf,0,len);
            }
            //关闭数据的输出  告诉服务器端 说我的图片已经传完了  避免服务器端一直等待
            socket.shutdownOutput();

            //接收来自于服务器端的数据,并显示到控制台上

            //1.获取输出流,用于接收数据
            is = socket.getInputStream();
            //因为此时要传输的是字符串(中文是占三个字节的)如果不使用ByteArrayOutputStream 有可能会乱码
            //ByteArrayOutputStream的作用是将写入的部分字符存在数组中,等完全读完后再一起输出  这样子就不会引起乱码
            baos = new ByteArrayOutputStream();
            //数据的读写操作
            byte[] cbuf1=new byte[5];
            int len1;
            while((len1=is.read(cbuf1))!=-1){
                baos.write(cbuf1,0,len1);
            }
            System.out.println(baos);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            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;
        FileOutputStream fos= null;
        OutputStream os = null;
        try {
            //指明服务的端口号
            ss = new ServerSocket(8890);
            //接收来自指定端口号的套接字
            socket = ss.accept();
            //获取输入流 用来接收数据
            is = socket.getInputStream();
            //实例化文件对象
            File file=new File("向涵之9.jpg");
            //实例化流对象
            fos = new FileOutputStream(file);
            //数据的读写操作
            byte[] cbuf=new byte[1024];
            int len;
            while((len=is.read(cbuf))!=-1){
                fos.write(cbuf,0,len);
            }
            System.out.println("图片传输完成");
            os = socket.getOutputStream();
            os.write("我已接收到向涵之图片".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null){
                try {
                    fos.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();
                }
            }
        }





    }

3.UDP的网络编程:

* UDP协议
* 将数据报、源、目的封装成数据包,不需要建立连接
* 每个数据报的大小限制在64K内
* 发送不管对方是否准备好,接收方收到也不确认,故是不可靠的连接
* 可以广播发送
* 发送数据结束时无需释放资源,开销小,速度快
* 比如看网络视频 发短信 发电报 发导弹

UDP网络编程的例子:

 @Test
    public void sender(){
        DatagramSocket socket= null;
        try {
            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);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket!=null){
                socket.close();
            }
        }

    }
    @Test
    public void receiver(){
        DatagramSocket socket= null;
        try {
            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()));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket!=null){
                socket.close();
            }
        }


    }

4.URL网络编程:

* 1.URL:统一资源定位符,对应着互联网的某一资源地址
* 2.格式:
* https://www.bilibili.com/video/BV1Qb411g7cz?p=627&spm_id_from=pageDriver
* 协议     域名(主机名加端口号)  资源地址           参数列表

常用方法:

public class URLTest {
    public static void main(String[] args) {
        try {
            URL url=new URL("https://www.bilibili.com/video/BV1Qb411g7cz?p=627&spm_id_from=pageDriver");
        /*
        public String getProtocol() 获取该主机的协议名
        public String getHost()   获取该URL的主机名
        public String getPort()   获取该URL的端口号
        public String getPath()   获取该URL的文件路径
        public String getFile()   获取该URL的文件名
        public String getQuery()  获取该URL的查询名
         */
            //public String getProtocol() 获取该主机的协议名
            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();
        }


    }
}

URL编程用例一:

public class URLTest1 {
    public static void main(String[] args){
        HttpURLConnection urlConnection = null;
        InputStream is = null;
        FileOutputStream fos= null;
        try {
            URL url=new URL("http://img.jutoula.com/201912/24/133207973.jpg");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            is = urlConnection.getInputStream();
            fos = new FileOutputStream("向涵之.jpg");
            byte[] cbuf=new byte[1024];
            int len;
            while((len=is.read(cbuf))!=-1){
                fos.write(cbuf,0,len);
            }
            System.out.println("下载完成");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(urlConnection!=null){
                urlConnection.disconnect();
            }

        }




    }
}



这篇关于java网络编程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程