Android UDP Code

Source: Internet
Author: User
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_bloc
			K_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 ();
 }
	}
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.