【网络编程】-- 04 UDP

2023-12-13 21:49:35

网络编程

6 UDP

6.1 初识Tomcat

服务端

  • 自定义 S
  • Tomcat S

客户端

  • 自定义 C
  • 浏览器 B

6.2 UDP

6.2.1 udp实现发送消息

接收端:

package com.duo.lesson03;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpServerDemo1 {
    public static void main(String[] args) throws Exception {

        //开放端口
        DatagramSocket datagramSocket = new DatagramSocket(9090);
        //接收数据包
        byte[] buffer = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length);

        datagramSocket.receive(datagramPacket);  //阻塞接收
        System.out.println(datagramPacket.getAddress().getHostAddress());
        System.out.println(new String(datagramPacket.getData(), 0, datagramPacket.getLength()));
        //关闭连接
        datagramSocket.close();

    }
}

发送端:

package com.duo.lesson03;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

//UDP不需要连接服务器
public class UdpClientDemo1 {

    public static void main(String[] args) throws Exception {
        //1.建立一个Socket用于发送包
        DatagramSocket datagramSocket = new DatagramSocket();

        //2.建一个包
        String msg = "您收到一条新消息";
        InetAddress inetAddress = InetAddress.getByName("localhost");
        int port = 9090;
        DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, inetAddress, port);

        //3.发送包
        datagramSocket.send(datagramPacket);

        //4.关闭流
        datagramSocket.close();
    }
}

运行结果:

image-20231208110004629

文章来源:https://blog.csdn.net/qq_51916086/article/details/134910348
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。