Android UDP

原创 2016年06月02日 00:04:23
package com.chy.socket;

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

import com.chy.global.GlobalValue;

public class UdpClient {

	private boolean isStop = false;
	private DatagramSocket datagramSocket = null;
	private onReceiveListener onReceiveListener = null;
	private ReadThread readThread = null;
	
	public interface onReceiveListener {
		public void onReceive(DatagramPacket packet);
	}

	class ReadThread extends Thread {

		@Override
		public void run() {
			byte[] buffer = new byte[GlobalValue.READ_BLOCK_SIZE];
			DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
			while (!isStop && !isInterrupted()) {
				try {
					datagramSocket.receive(packet);
					if (onReceiveListener != null) {
						onReceiveListener.onReceive(packet);
					}
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}

	}

	public UdpClient(int port, onReceiveListener onReceiveListener) {
		try {
			datagramSocket = new DatagramSocket(port);
		} catch (SocketException ex) {
			ex.printStackTrace();
		}
		if (datagramSocket == null) {
			return;
		}
		this.onReceiveListener = onReceiveListener;
		readThread = new ReadThread();
		readThread.start();
	}

	public synchronized boolean send(byte[] buffer) {
		boolean result = false;
		if(datagramSocket != null) {
			DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
			try {
				datagramSocket.send(packet);
				result = true;
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	public void close() {
		isStop = true;
		if(readThread != null && !readThread.isInterrupted()) {
			readThread.interrupt();
			readThread = null;
		}
		if (datagramSocket != null) {
			datagramSocket.close();
		}
	}
}

版权声明:转载请注明出处——http://blog.csdn.net/chy555chy/article 举报

相关文章推荐

返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)