Code example for DatagramSocket

Methods: close, receive, setSoTimeout

0
			e.printStackTrace();
			return -1; 
		} 
 
		try { 
			mSocket = new DatagramSocket(mPort);
 
		} catch (SocketException e) {
			e.printStackTrace();
			return -2; 
		} 
		 
		try { 
			mSocket.setSoTimeout(10000);
 
		} catch (SocketException e) {
			e.printStackTrace();
			return -3; 
		} 
 
		return 0; 
	} 
 
	// set socket for sending (fails if closed) 
	boolean prepForBroadcast() { 
		try { 
			mSocket.setBroadcast(true);
		} catch (SocketException e) {
			e.printStackTrace();
			return false; 
		} 
		return true; 
	} 
 
	// attempts to send packet 
	boolean sendPack() { 
 
		initSocket(); 
		preInit = true;
		 
		prepForBroadcast(); 
 
		try { 
			currentTime = "" + System.currentTimeMillis();
			byteMessage = currentTime.getBytes();
			mPack = new DatagramPacket(byteMessage, byteMessage.length,
					sendAddress, mPort);
			mSocket.send(mPack);
		} catch (IOException e) {
			e.printStackTrace();
			return false; 
		} 
		return true; 
	} 
 
	// attempts to receive packet 
	boolean receivePack() { 
	 
		if (!preInit) initSocket();
		 
		DatagramPacket newPack = new DatagramPacket(receivedMessage,
				byteMessage.length);
		try { 
			mSocket.receive(newPack);
			mSocket.close();
			success = true;
		} catch (IOException e) {
			success = false;
			e.printStackTrace();
			return false;