java,UDP编程,实现发送端A和接收端B通信

//发送端A
package udp;

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

public class SenderA {
	public static void main(String[] args) throws IOException {
		System.out.println("这里是发送端A");
		//创建监听端口
		DatagramSocket socket = new DatagramSocket(9998);
		byte[] buf = new byte[1024];
		int length = buf.length;
		DatagramPacket packet = new DatagramPacket(buf, length, InetAddress.getLocalHost(), 9999);
		packet.setData("b你好".getBytes());
		socket.send(packet);
		
		//接收回复的消息
		DatagramPacket rPacket = new DatagramPacket(buf, length);
		socket.receive(rPacket);
		int rLength = rPacket.getLength();
		byte[] rb = rPacket.getData();
		String s = new String(rb, 0, rLength);
		System.out.println(s);
		socket.close();
		
	}
}
//接收端B
package udp;

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

public class ReceiverB {
	public static void main(String[] args) throws IOException {
		DatagramSocket socket = new DatagramSocket(9999);//创建监听端口
		System.out.println("这里是接收端B");
		byte[] buf = new byte[1024];
		DatagramPacket packet = new DatagramPacket(buf, buf.length);//创建接收的数据包
		socket.receive(packet);//将发送数据的包转存到接收数据的包
		int length = packet.getLength();//接收到的数据的长度
		byte[] data = packet.getData();//把接收的数据存入
		String s = new String(data, 0, length);
		System.out.println(s);
		
		//开始给A回复消息
		int sendLength = buf.length;
		DatagramPacket sendPacket = new DatagramPacket(buf, sendLength, InetAddress.getLocalHost(), 9998);
		sendPacket.setData("A你好,我已经收到你发送的消息".getBytes());
		socket.send(sendPacket);
		socket.close();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值