Java学习总结2:网络编程实例

本文总结了Java中的网络编程,包括查询主机IP、使用URL访问网络资源,以及TCP/IP下的Socket通信步骤。对于Socket通信,详细阐述了服务器端和客户端的建立连接、数据传输和关闭连接过程。同时提到了UDP无连接的数据报通信,涉及DatagramSocket和DatagramPacket的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、查询个人主机的IP地址与Internet上WWW服务器的IP地址
Internet上主机的地址有两种表示方式,即域名和IP地址,通常使用InetAddress类的一些常用方法可直接获取,不过InetAddress类无构造方法,因此不能使用new运算符创建该类对象,通常使用它提供的静态方法获得。而static方法通常会产生UnknownHostException 异常,因此程序中也需捕获异常。

public static void main(String[] args) {
        try {
            /*查询本机地址 */
            
            InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");	//127.0.0.1是个人主机的IP地址
            System.out.println(inetAddress1);
            InetAddress inetAddress11 = InetAddress.getByName("localhost");	//可以用主机名代替IP地址
            System.out.println(inetAddress11);
            
            InetAddress inetAddress12 = InetAddress.getLocalHost();
            System.out.println(inetAddress12);

            //查询网站IP的地址
            InetAddress inetAddress2 = InetAddress.getByName("www.tomcat.com");
            System.out.println(inetAddress12);

            /* 常用方法 */
            System.out.println(inetAddress2.getHostAddress());
            System.out.println("规范自己的名字:" + inetAddress2.getCanonicalHostName());
            System.out.println("IP:" + inetAddress2.getHostAddress());
            System.out.println("域名/个人电脑的名字:" + inetAddress1.getHostName());
        }
        catch (UnknownHostException e)
        {
            e.printStackTrace();	//可以不用写该内容
        }

    }

二、使用URL类访问网络资源
可通过URL直接读取网络上服务器中的文件内容。一般分为三个步骤:一是创建URL类对象;二是利用URL类的openStream()方法获得对应的InputStream类的对象;三是通过InputStream对象来读取文件内容。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class URLfile {
    public static void main(String[] args) {
        //本例访问网易云音乐的网页板块
        String urlName = "https://music.163.com/#/discover/playlist";
        if(args.length >0) urlName = args[0];
        new URLfile().display(urlName);
    }
    public void display(String urlName)
    {
        try {
            URL url1 = new URL(urlName); //创建URL类对象url1;
            InputStreamReader in = new InputStreamReader(url1.openStream());
            BufferedReader br = new BufferedReader(in);
            String aLine;
            while ((aLine = br.readLine()) != null)
                System.out.println(aLine);
        }
        catch (MalformedURLException murle)  //创建URL对象时,若发生错误,系统会发生该异常,为非运行时异常需捕获处理
        {
            System.out.println(murle);
        }
        catch (IOException ioe) //该异常类是在非运行时最常用的异常类,所有输入输出相关命令的情况都必须处理IOException所引发的异常
        {
            System.out.println(ioe);
        }
    }
}

三、TCP/IP下的Socket网路通信
Socket通信的步骤:

  1. 在服务器端创建一个ServerSocket对象,并指定端口号;
  2. 运行ServerSocket的accept()方法,等候客户请求;
  3. 客户端创建一个Socket对象,指定服务器的IP地址和端口号,向服务器端发出连
    接请求;
  4. 服务器端接收到客户端请求后,创建Socket对象与客户端建立连接;
  5. 服务器端和客户端分别建立输人输出数据流,进行数据传输;
  6. 通信结束后,服务器端和客户端分别关闭相应的Socket连接;
  7. 服务器端程序运行结束后,调用ServerSocket对象的Close()方法停止等候客户端
    请求。

注:下例代码中服务器端只建立了输入流,客户端仅建立了输出流。

服务器端的程序代码如下:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServerDemo {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;

        try {
            //1.服务端的地址
            serverSocket = new ServerSocket(9999);
            //2.等待客户端连接过来
            socket = serverSocket.accept();
            //3.读取客户端的消息
            is = socket.getInputStream();

            // 管道流
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while((len = is.read(buffer)) != -1){
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());
        }

        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(socket != null)
            {
                try {
                    socket.close();
                }catch(IOException e)
                {
                    e.printStackTrace();
                }
            }
            if(serverSocket != null)
            {
                try {
                    serverSocket.close();
                }catch(IOException e)
                {
                    e.printStackTrace();
                }
            }

        }
    }
}
客户端程序代码如下:
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClientDemo {

    public static void main(String[] args) {
        OutputStream os = null;
        Socket socket = null;

        try {
            //1.要知道服务器的地址、端口号
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            int port = 9999; //端口号
            //2.建立一个socket连接
            socket = new Socket(serverIP,port);
            //3.发送消息 IO流
            os = socket.getOutputStream();
            os.write("hello,welcom to learn java".getBytes());

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

    }
}

UDP无连接的数据报通信
数据包通信的基本模式:客户端将数据打包,形成数据包,然后将其发往目的地;服务器端接收客户端发来的数据包,查看其内容。
Java中用于无连接的数据包通信有DatagramSocket和DatagramPacket两类。DatagramPacket类用于在发送端将待发送的数据打包,在接收端将收到的数据拆包;DatagramSocket类用于实现数据报通信的过程中的数据包的发送与接收

客户端代码如下:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpClientDemo {
    public static void main(String[] args) throws Exception  {
        //1.建立一个UDP Socket对象
        DatagramSocket socket = new DatagramSocket();

        //2.建个包
        String msg = "hello Serverdemo!";
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9090;

        //3.数据打包
        DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length ,localhost,port); //数据/数据的长度起始/要发送给谁

        //3.发送包
        socket.send(packet);

        //4.关闭流
        socket.close();
    }
}
服务器端代码如下:
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPServerDemo {
    public static void main(String[] args) throws Exception {
        //开放端口
        DatagramSocket socket = new DatagramSocket(9090);  //捕获异常

        //接收数据包
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
        socket.receive(packet);

        //输出数据包内容
        System.out.println(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData(), 0, packet.getLength()));

        //关闭连接
        socket.close();
    }
}

注:两种通信模式的代码仅只是表达了其基本模式的程序代码,还有许多可补充之处,该代码仅供参考。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值