Java网络编程二 UDP通信

本文提供了一个简单的UDP通信实例,包括服务端与客户端的Java代码实现。服务端监听1000端口接收客户端发送的数据包,并打印客户端的IP地址、端口号及发送的内容。客户端则构造包含整数与字符串信息的数据包并发送到指定的服务端。

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

1. 服务端


import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpServer {

    public static void main(String[] args) {
        try {
            DatagramSocket ds = new DatagramSocket(1000);
            byte[] buf = new byte[1024];
            while(true){
                DatagramPacket dp = new DatagramPacket(buf, buf.length);
                ds.receive(dp);
                System.out.println("client ----> IP: " + dp.getAddress().getHostAddress() + ", port: " + dp.getPort());
                DataInputStream dis = new DataInputStream(new ByteArrayInputStream(dp.getData()));
                System.out.println(dis.readInt());
                BufferedReader d = new BufferedReader(new InputStreamReader(dis));
                System.out.println(new String(d.readLine()));
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

 

2.  客户端


import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class UdpClient {

    public static void main(String[] args) {
        try {
            DatagramSocket ds = new DatagramSocket();
           
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(baos);
            dos.writeInt(200);
            dos.write("你好".getBytes());
            System.out.println("字节数: " + dos.size());
            byte[] buf = baos.toByteArray();
            DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress("127.0.0.1", 1000));
           
            ds.send(dp);
            ds.close();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值