package org.kne.cloud.network;

import java.io.Closeable;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.function.Consumer;

public class DatagramSocketListener implements Closeable,AutoCloseable{
	private DatagramServerSocket serverSocket;
	public DatagramServerSocket getDatagramServerSocket() {
		return serverSocket;
	}

	private volatile boolean flag=true;
	
	private Consumer<DatagramSocket>con;
	private Runnable r=new Runnable() {
		@Override
		public void run() {
			while(flag){
				try {
					DatagramSocket soce=serverSocket.accept();
					ThreadTool.makeVThreadIfSupport("端口监听处理线程",()->{
						con.accept(soce);
					}).start();
				}catch(SocketException e) {e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	};
	private MultiProtocolSocketAddress multiProtocolSocketAddress;
	
	public DatagramSocketListener(MultiProtocolSocketAddress multiProtocolSocketAddress) throws IOException {
		this.multiProtocolSocketAddress = multiProtocolSocketAddress;
		open();
	}
	public DatagramSocketListener(DatagramServerSocket tserverSocket) throws IOException {
		this.serverSocket=tserverSocket;
		open();
	}

	private void open() throws IOException {
		if(serverSocket==null)
			serverSocket= multiProtocolSocketAddress.listenDatagramServerSocket();
		//new Thread(r).start();
		ThreadTool.makePThreadIfSupport("端口监听线程",r).start();
	}
	public void close() {
		flag=false;
		if(serverSocket!=null) {
			serverSocket.close();
			serverSocket=null;
		}
	}
	
	

	public MultiProtocolSocketAddress getMultipurposeSocketAddress() {
		return multiProtocolSocketAddress;
	}

	public Consumer<DatagramSocket> getCon() {
		return con;
	}

	public void setCon(Consumer<DatagramSocket> con) {
		this.con = con;
	}
	
}
