网络编程---UDP

本文介绍了一个简单的UDP聊天程序实现过程,使用Java中的DatagramSocket和DatagramPacket类完成客户端之间的消息收发。程序通过两个独立的线程分别处理消息发送与接收,并能够处理用户的退出操作。

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

主要用两个类 DatagramSocket DatagramPacket
连接步骤:

  • 建立发送端,接收端。
  • 建立数据包。
  • 调用Socket的发送接收方法
  • 关闭Socket。

发送端与接收端是两个独立的运行程序。

这里写图片描述

下面演示:
要求:UDP聊天程序
通过键盘录入获取要发送的信息。
将发送和接收分别封装到两个线程中



public class UDPChat {
    public static void main(String[] args) {
        try {
            DatagramSocket send = new DatagramSocket(10001);
            DatagramSocket receive = new DatagramSocket(10002);

            new Thread(new Send(send) ).start();
            new Thread(new Receive(receive)).start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

class Send implements Runnable{
    private DatagramSocket ds;
    public Send(DatagramSocket send) {
        this.ds = send;
    }

    @Override
    public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            while( (line=br.readLine())!=null ){
                byte buf[] = line.getBytes();
                //要用接收方的ip和接收端口
                DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.31.168"), 10004);
                ds.send(dp);
                if("over".equals(line)){
                    break;
                }
            }
            ds.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class Receive implements Runnable{
    private DatagramSocket ds;
    public Receive(DatagramSocket receive) {
        this.ds = receive;
    }

    @Override
    public void run() {
        try {
            byte buf[] = new byte[1024];//大小够存储一行就可以
            while(true){
                //接收数据
                DatagramPacket dp = new DatagramPacket(buf, buf.length);
                ds.receive(dp);
                //解析数据
                String ip = dp.getAddress().getHostAddress();
                String info= new String(dp.getData(),0,dp.getLength());//只能用dp.getlength不能要byte的length
                System.out.println(ip+"说:"+info);
                if("over".equals(info)){
                    System.out.println(ip+"离开聊天室....");
                    //break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值