司马懿的西山居

如果觉得有帮助,就顶顶顶一个,或者关注、关注、关注一下,转载请注明出处。...

Android UDP

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 https://blog.csdn.net/chy555chy/article/details/51560186
个人分类: Android
上一篇Android Tcp服务器端
下一篇Android UncaughtExceptionHandler 记录异常并重启程序
想对作者说点什么? 我来说一句

android发送UDP广播demo

2014年06月21日 2.79MB 下载

没有更多推荐了,返回首页

关闭
关闭