欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java简单工具:UDP通讯工具类(测试使用)

程序员文章站 2022-06-29 18:54:10
...
package udppacket;

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

public class UDPClientAPI {
	DatagramSocket client=null;
	InetAddress addr=null;
	int port=-1;
	IUDPListener listener;
	public UDPClientAPI(String desAddr,int desPort,IUDPListener listener) throws IOException{
		client = new DatagramSocket();
		addr = InetAddress.getByName(desAddr);
		port=desPort;
		this.listener=listener;
	}
	
	public void sendData(byte[]bytes) throws IOException{
		if (addr==null||port==-1) {
			throw new NullPointerException("请重新初始化");
			//return;
		}
		DatagramPacket sendPacket = new DatagramPacket(bytes, bytes.length,addr, port);
		client.send(sendPacket);
	}

	
	/**
	 * 简单的循环执行读取数据
	 * @throws IOException 
	 */
	public void simpleWaitingRead(boolean isRead) throws IOException{
		if (isRead) {
			if (!isCycle) {//未进行循环执行循环读取
				isCycle=true;//执行循环
				CycleRead();//执行循环操作
			}
		}else {
			if (isCycle) {//正在运行时执行停止循环
				isCycle=false;//停止循环
			}
			
		}
		
	}
	
	boolean isCycle=false;
	/**
	 * 执行循环读取操作
	 * @throws IOException 
	 */
	public void CycleRead() {
		new Thread(){public void run() {
			while(isCycle){
				System.out.println("into the cycleRead");
				byte[]read_b=new byte[2048];//作为数据缓存区,读取数据最大长度无法超出2K
				DatagramPacket recvPacket = new DatagramPacket(read_b, read_b.length);//缓存区装进包中
				try {
					client.receive(recvPacket);//阻塞读取数据
					byte[]vaild_b=new byte[recvPacket.getLength()];//有效数据
					System.arraycopy(read_b, 0, vaild_b, 0, vaild_b.length);//取出有效数据
					listener.onReceiveData(vaild_b);//通过监听器回调有效数据
				} catch (IOException e) {
					if (!e.getMessage().equals("Socket closed")) {
						e.printStackTrace();
					}
				}//进行包读取,阻塞型
			}
		};}.start();
	}

	/**
	 * 关闭所有
	 */
	public void CloseAll(){
		isCycle=false;
                port=-1;
                if (client!=null&&!client.isClosed()) {
                     client.close();
                }
         }
}