数据的接收与发送(练习)

发送方:Demo002Send.java

package com.shsxt.day09.udp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;

/*
 * 发送方:
 * 1、准备一个数据报  发送工具   DatagramSocket
 * 2、准备数据
 * 3、准备数据报包     (数据+ 地址(ip+端口号))
 * 4、发送 (使用数据报发送出数据报包)
 * 5、释放资源
 */
public class Demo002Send {
    public static void main(String[] args)throws Exception {

        DatagramSocket socket = new DatagramSocket(2626);

        //byte[] msg = "hello".getBytes();
        // 输入数据发送
        /*Scanner sc = new Scanner(System.in);
        String m = sc.nextLine();
        byte[] msg = m.getBytes();*/
        // System.in   -> 标准输入流
        BufferedReader bis = new BufferedReader(new InputStreamReader(System.in));
        byte[] msg = bis.readLine().getBytes();


        InetAddress address = InetAddress.getByName("127.0.0.1");
        InetSocketAddress socketAddress = new InetSocketAddress(address, 3535);

        DatagramPacket p = new DatagramPacket(msg, msg.length,socketAddress);

        socket.send(p);
        socket.close();


        DatagramSocket socket1 = new DatagramSocket(5454);
        byte[] ms = new byte[1024];
        DatagramPacket dp = new DatagramPacket(ms,ms.length);
        socket1.receive(dp);
        int len = dp.getLength();
        System.out.println(new String(ms,0,len));

        socket1.close();


    }
}

接收方:Demo002Receive

package com.shsxt.day09.udp;

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

/*
 * 1、准备一个数据报  接收数据的工具    指定自己在哪个端口接收
 * 2、准备接收数据的容器 
 * 3、准备一个空的数据报包
 * 4、接收
 * 5、释放资源
 */
public class Demo002Receive {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(3535);

        byte[] msg = new byte[1024];
        DatagramPacket packet = new DatagramPacket(msg,msg.length);
        //    阻塞在此等待数据
        socket.receive(packet);

        int len = packet.getLength();

        String str = new String(msg,0,len);
        System.out.println(str);


        // 获取发送方信息, 准备回复信息
        InetAddress address = packet.getAddress();
        InetSocketAddress socketAddress = new InetSocketAddress(address, 5454);

        String ms = "来自对方回复:" + str;

        DatagramPacket dp = new DatagramPacket(ms.getBytes(),ms.getBytes().length,socketAddress);
        socket.send(dp);

        socket.close();



    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值