Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android系統教程 >> Android開發教程 >> Android UDP代碼

Android UDP代碼

編輯:Android開發教程

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();
		}
	}
}

URL:http://www.bianceng.cn/OS/extra/201608/50409.htm

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved