Java——网络编程

Java—网络编程

(学习Java网络编程时,需要有计算机网络的基础知识)

InetAddress类

相关方法:

  1. 获取本机InetAddress对象 getLocalHost
  2. 根据指定主机名/域名获取ip地址对象 getByName
  3. 获取InetAddress对象的主机名 getHostName
  4. 获取InetAddress对象的地址 getHostAddress
**
 * 演示InetAddress 类的使用
 */
public class API_ {
    public static void main(String[] args) throws UnknownHostException {

        //获取本机InetAddress对象
        InetAddress localHost = InetAddress.getLocalHost();
        System.out.println(localHost);

        //根据指定主机名,获取InetAddress对象
        InetAddress host1 = InetAddress.getByName("LAPTOP-LGPK08DR");
        System.out.println(host1);

        //根据域名返回InetAddress对象,比如www.baidu.com
        InetAddress host2 = InetAddress.getByName("www.baidu.com");
        System.out.println(host2);

        //通过InetAddress对象,获取对应的地址
        String hostAddress = host2.getHostAddress();
        System.out.println(hostAddress);

        //通过InetAddress对象,获取对应的主机名
        String hostName = host2.getHostName();
        System.out.println(hostName);


    }
}


/*  运行结果:
LAPTOP-LGPK08DR/192.168.2.29
LAPTOP-LGPK08DR/192.168.2.29
www.baidu.com/220.181.38.150
220.181.38.150
www.baidu.com
*/

Socket

基本介绍:

  1. 套接字(Socket)开发网络应用程序被广泛采用,以至于成为事实上的标准。
  2. 通信段两端都要有Socket,是两台机器间通信段端点
  3. 网络通信其实就是Socket间的通信
  4. Socket允许程序把网络连接当成一个流,数据在两个Socket间通过IO传输
  5. 一般主动发起通信的应用程序属于客户端,等待通信请求的为服务端

Socket两种编程方式:TCP编程(可靠) 和 UDP编程(不可靠)

TCP编程

基本介绍:

  1. 基于客户端——服务器的网络通信
  2. 底层使用的是TCP/IP协议
  3. 应用场景举例:客户端发送数据,服务端接受并显示控制台
  4. 基于Socket的TCP编程
  5. 在这里插入图片描述

案例一:
在这里插入图片描述

public class SocketTCP01Sever {
    public static void main(String[] args) throws IOException {

        //在本机的9999端口监听,等待连接
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务器端,在9999端口监听,等待连接...");

        //当没有客户端连接9999端口时,程序就会阻塞,等待连接
        //如果有客户端连接,则会返回Socket对象,程序继续
        Socket socket = serverSocket.accept();

        InputStream inputStream = socket.getInputStream();
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(buf))!=-1){
            System.out.print(new String(buf,0,readLen));
        }

        inputStream.close();
        socket.close();
        serverSocket.close();
        System.out.println("\n服务器端退出....");

    }
}
public class SocketTCP01Client {
    public static void main(String[] args) throws IOException {

        //连接服务器(ip,端口),连接本机9999端口
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        //连接上后,生成Socket,通过socket.getOutputStream()
        //得到和socket对象关联的输出流对象

        OutputStream outputStream = socket.getOutputStream();

        outputStream.write("hello,Sever".getBytes());
        outputStream.close();
        socket.close();
        System.out.println("客户端退出........");
    }
}

案例二:

在这里插入图片描述

public class SocketTCP02Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务器端等待连接.......");
        Socket socket = serverSocket.accept();

        InputStream inputStream = socket.getInputStream();
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(buf))!=-1){
            System.out.println(new String(buf,0,readLen));
        }

        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello,client".getBytes());
        socket.shutdownOutput();

        outputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
        System.out.println("服务器端已退出.......");
    }
}
public class SocketTCP02Client {
    public static void main(String[] args) throws IOException {

        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello,server".getBytes());
        socket.shutdownOutput();
        InputStream inputStream = socket.getInputStream();
        byte[] buf = new byte[1024];
        int readLen = 0;
        while((readLen = inputStream.read(buf))!=-1){
            System.out.println(new String(buf,0,readLen));
        }

        outputStream.close();
        inputStream.close();
        socket.close();
        System.out.println("客户端已退出.........");
    }
}

【注意】:在写完输入流后需要给出结束标志,socket.shutdownOutput();否则程序一直处于等待状态中

案例三:

在这里插入图片描述

public class SocketTCP03Client {
    public static void main(String[] args) throws IOException {

        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);

        OutputStream outputStream = socket.getOutputStream();
        String filePath = "F:\\javaIO\\aaa.png";
        FileInputStream fileInputStream = new FileInputStream(filePath);
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen = fileInputStream.read(buf)) != -1) {
            outputStream.write(buf, 0, readLen);
        }
        socket.shutdownOutput();

        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String str = bufferedReader.readLine();
        System.out.println(str);


        inputStream.close();
        fileInputStream.close();
        outputStream.close();
        socket.close();
        System.out.println("客户端已退出......");


    }
}
public class SocketTCP03Server {
    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务器端等待连接(9999端口)");
        Socket socket = serverSocket.accept();

        InputStream inputStream = socket.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream("src\\bbb.png");
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(buf))!=-1){
                fileOutputStream.write(buf,0,readLen);
        }
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("收到图片");
        bufferedWriter.newLine();
        bufferedWriter.flush();

        outputStream.close();
        fileOutputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
        System.out.println("服务器端已退出.......");
    }
}

netstat指令

  1. netstat -an 可以查看当前主机网络情况,包括端口监听情况,和网络连接情况
  2. netstat -an | more 可以分页显示
  3. 要求在dos控制台下执行
    在这里插入图片描述

【说明】

  1. Listening 表示某个端口在监听
  2. 如果有一个外部程序(客户端)连接该端口,就会显示一条连接信息
  3. 可以输入 ctrl + c 退出程序
  4. netsata -anb 可以查看详细端口监听情况

当客户端连接到服务器后,实际上客户端也是通过一个端口和服务器进行通讯的,这个端口是TCP/IP分配的,是不确定的,是随机的。

UDP编程

基本介绍:

  1. 类DatagramSocket 和 DatagramPacket 实现了基于 UDP 协议网络程序
  2. UDP数据报通过数据报套接字 DatagramSocket 发送和接收,系统不保证UDP数据报一定能够安全送到目的地,也不能确定什么时候可以抵达
  3. DatagramPacket 对象封装了UDP数据报,在数据报中包含了发送端的IP地址和端口号以及接收端的IP地址和端口号
  4. UDP协议中每个数据报都给出了完整的地址信息,因此无须建立发送方和接收方的连接

基本流程:

  1. 核心的两个类/对象 DatagramSocket 与 DatagramPacket
  2. 建立发送端,接收端
  3. 建立数据包 (DatagramPacket)
  4. 调用DatagramSocket的发送,接收方法
  5. 关闭DatagramSocket

UDP说明:

  1. 没有明确的服务端和客户端,演变成数据的发送端和接收端
  2. 接收数据和发送数据是通过 DatagramSocket 对象完成
  3. 将数据封装到DatagramPacket对象,需要进行拆包,取出数据
  4. DatagramSocket 可以指定在哪个端口接收数据
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值