Java 实现简单的UDP通信

创建服务器:

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

public class TestUDPServer {
	public static void main(String args[]){
		byte[] buf=new byte[1024];
		DatagramPacket dp=null;
		DatagramSocket ds=null;
	    dp=new DatagramPacket(buf,buf.length);//创建一个数据包裹,用字节数组buf来接收数据
		try {
			ds=new DatagramSocket(6666);//创建数据报套接字并将其绑定到6666的本机端口
		} catch (SocketException e) {
			e.printStackTrace();
		}
		while(true){
			try {
				ds.receive(dp);
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println(new String(buf,0,dp.getLength()));
		}
	}

}

创建客户端:

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

public class TestUDPClient {

	public static void main(String[] args) {
		byte[] buf=new String("hellow").getBytes();
		DatagramPacket dp=null;
		try {
			dp=new DatagramPacket(buf,buf.length,new InetSocketAddress("127.0.0.1",6666));
		} catch (SocketException e) {
			e.printStackTrace();
		}
        DatagramSocket ds=null;
        try {
			ds=new DatagramSocket(8888);
		} catch (SocketException e) {
			e.printStackTrace();
		}
        try {
			ds.send(dp);
		} catch (IOException e) {
			e.printStackTrace();
		}
        ds.close();
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值