Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: DatagramChannel - UDP receiving OK, but unable to send data :(

  1. #1
    Junior Member
    Join Date
    Apr 2014
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default DatagramChannel - UDP receiving OK, but unable to send data :(

    I am trying to connect to a local application over UDP... I have tried blocking, non-blocking, connecting, not connection, reading and re-reading the Oracle docs, and am pretty much google-e-eyed now : Here's my latest refactoring:

     
     
    package my.comm;
     
    import my.myMethods;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.DatagramChannel;
    import java.util.LinkedList;
    import java.util.Queue;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
     
    /**
     *
     * @author dave
     */
    public class myConnection implements Runnable {
    	DatagramChannel datagramChannel;
     
    	private final String HOST = "127.0.0.1";
    	private final int PAYMENT_PORT = 4444;
    	private final int MY_PORT = 8888;
     
    	private final Queue<byte[]> incommingDataPackets = new LinkedList();
    	private final Queue<byte[]> outgoingDataPackets = new LinkedList();
     
    	private final ExecutorService exec = Executors.newFixedThreadPool(1);
    	private final myMethods myMethods = new myMethods();
     
    	private static final Logger log = LogManager.getLogger();
     
    	public myConnection() throws IOException {
    		datagramChannel = DatagramChannel.open();
    		datagramChannel.bind(new InetSocketAddress(HOST, PAYMENT_PORT));
    		datagramChannel.connect(new InetSocketAddress(HOST, MY_PORT));
    		datagramChannel.configureBlocking(true);
     
    		myReceiver myReceiver = new myReceiver(this, datagramChannel.socket());
    		Thread mtdrThread = new Thread(myReceiver);
    		exec.execute(mtdrThread);
    	}
     
    	public synchronized byte[] receiveData() {
    		byte[] receivedBytes = new byte[0];
    		if(incommingDataPackets.size() > 0) {
    			receivedBytes = incommingDataPackets.remove();
    			log.debug("receiving {}", myMethods.hexRepresentationOfByteBuffer(receivedBytes));
    		}
    		return receivedBytes;
    	}
     
    	public synchronized void transmitData(byte[] sendData) {
    		outgoingDataPackets.add(sendData);
    		notifyAll();
    	}
     
    	@Override
    	public void run() {
    		try {
    			while(true){
    				while(outgoingDataPackets.size() > 0) {
    					byte[] outgoingBytes = outgoingDataPackets.remove();
     
    					ByteBuffer outgoingByteBuffer = ByteBuffer.allocate(outgoingBytes.length);
    					outgoingByteBuffer.clear();
    					outgoingByteBuffer.put(outgoingBytes);
    					outgoingByteBuffer.flip();
     
    					log.debug("sending	{}", myMethods.hexRepresentationOfByteBuffer(outgoingBytes));
    					int sentBytes = datagramChannel.write(outgoingByteBuffer);
    					log.debug("sent {} bytes of data ", sentBytes);
    				}
    			}
    		} catch (IOException ex) {
    			log.fatal("IOException!	{}", ex.getMessage());
    		}
    	}
     
    	public synchronized void addIncommingDatagramGuts(byte[] receivedBytes) {
    		incommingDataPackets.add(receivedBytes);
    		notifyAll();
    	}
    }

    And the thread which receives the data:

    package my.comm;
     
    import my.myMethods;
    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.nio.ByteBuffer;
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;/**
     *
     * @author Dave
     */
    class myReceiver implements Runnable {
    	private final DatagramSocket datagramSocket;
    	private DatagramPacket datagramPacket;
     
    	int MAX_PACKET_SIZE = 1500;
    	byte[] incommingBytes = new byte[MAX_PACKET_SIZE];
     
    	private final myConnection myConnection;
    	private final myMethods myMethods = new myMethods();
    	private static final Logger log = LogManager.getLogger();
     
    	myReceiver (myConnection myConnection, DatagramSocket datagramSocket) {
    		this.myConnection = myConnection;
    		this.datagramSocket = datagramSocket;
    	}
     
    	@Override
    	public void run() {
    		while(true) {
    			try {
    				datagramPacket = new DatagramPacket(incommingBytes, MAX_PACKET_SIZE);
    				while(true){
    					datagramSocket.receive(datagramPacket);
    					myConnection.addIncommingDatagramGuts(myMethods.trimFrame(datagramPacket.getData()));
    				}
    			} catch (IOException ex) {
    				log.error("IOException!	{}", ex.getMessage());
    			}
    		}
    	}
    }

    All assistance is much appreciated!!!


    *** EDIT ****
    You need this file as well too compile the program - as well as jog4j2...

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package my;
     
    import java.io.Serializable;
    import java.nio.ByteBuffer;
    import java.text.DecimalFormat;
    import java.util.Arrays;
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
     
    /**
     *
     * @author Dave
     */
    public class myMethods implements Serializable {
    	private static final long serialVersionUID = 1L;
     
    	private static final Logger log = LogManager.getLogger();
     
    	/*
    	 * used to remove frame escapes and apply the frame mask to the 'dirty' bytes
    	 */
    	public byte[] cleanData(byte[] buffer) {
    		log.debug(hexRepresentationOfByteBuffer(buffer));
     
    		int cleanIndex = 0;
    		byte[] cleaningBuffer = new byte[buffer.length];
    		byte[] cleanedBuffer;
     
     
    		for(int index = 0; index < buffer.length; index++) {
    			cleaningBuffer[cleanIndex++] = buffer[index] == myConstants.frameEscape ? (byte)(buffer[++index] ^ myConstants.frameMask) : buffer[index];
    		}
     
    		cleanedBuffer = new byte[cleanIndex];
     
    		System.arraycopy(cleaningBuffer, 0, cleanedBuffer, 0, cleanIndex);
    		log.debug(hexRepresentationOfByteBuffer(cleanedBuffer));
    		return cleanedBuffer;
    	}
     
    	public byte[] trimFrame(byte[] buffer) {
    		if(buffer.length == 0)
    			return new byte[0];
     
    		int trimmedIndex = 0;
    		byte[] trimmedBytes;
     
    		boolean foundFirstFrameFlag = false;
    		boolean foundLastFrameFlag = false;
     
    		for(int index = 0; index < buffer.length; index++){
    			if(!foundFirstFrameFlag && buffer[index] == Byte.parseByte("7E", 16)) {
    				foundFirstFrameFlag = true;
    				index++;
    			} else
    				foundLastFrameFlag = foundFirstFrameFlag && buffer[index] == Byte.parseByte("7E", 16) ? true : foundLastFrameFlag;
    			if(foundLastFrameFlag)
    				break;
    			buffer[trimmedIndex++] = buffer[index];
    		}
     
    		trimmedBytes = new byte[trimmedIndex];
     
    		System.arraycopy(buffer, 0, trimmedBytes, 0, trimmedIndex);
    		return cleanData(trimmedBytes);
    	}
     
    	public String hexRepresentationOfByteBuffer(byte[] bytes) { 
    		StringBuilder stringBuilder = new StringBuilder();
    		for (int index = 0; index < bytes.length; index++) {
    			stringBuilder.append(hexRepresentationOfByte(bytes[index]));
    			if(index<bytes.length - 1)
    				stringBuilder.append(", ");
    		}
    		return stringBuilder.toString();
    	}
     
    	public String hexRepresentationOfByte(byte theByte) {
    		return String.format("%02x", theByte).toUpperCase();
    	}
    }
    Last edited by cr0ck3t; April 29th, 2014 at 02:00 PM. Reason: added additional file so it will compile


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: DatagramChannel - UDP receiving OK, but unable to send data :(

    How do you compile and test the program? The posted code won't compile without errors: missing import statements.

    Also posted at: http://www.java-forums.org/advanced-...send-data.html
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Apr 2014
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: DatagramChannel - UDP receiving OK, but unable to send data :(

    Quote Originally Posted by Norm View Post
    How do you compile and test the program? The posted code won't compile without errors: missing import statements.
    Sorry about that - the forum initially told my that I could not post my first thread as it either contained too many references to URL's or had bad language... tried stripping those out to get rid of "URLs" in the event the sentry software was being a little over zealous Here they are... Have added them now - let me know if I missed anything else... it was an early morning most and I was feeling a little

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: DatagramChannel - UDP receiving OK, but unable to send data :(

    How is the code executed for testing? I don't see any main() methods.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Apr 2014
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: DatagramChannel - UDP receiving OK, but unable to send data :(

    putting together some testing code now - going to blame that oversight on the lack of sleep...

  6. #6
    Junior Member
    Join Date
    Apr 2014
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: DatagramChannel - UDP receiving OK, but unable to send data :(

    Here's a working rendition my.zip (but it is still not actually 'working')

    Thanks again for your help in this

  7. #7
    Junior Member
    Join Date
    Apr 2014
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: DatagramChannel - UDP receiving OK, but unable to send data :(

    definitely going to blame that issue on 3 am coding... missed a
    try{ Thread.sleep(500); } catch (InterruptedException ignore) { }
    in a while(true) loop :S
    Last edited by cr0ck3t; April 29th, 2014 at 04:20 PM.

  8. #8
    Junior Member
    Join Date
    Apr 2014
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: DatagramChannel - UDP receiving OK, but unable to send data :(

    in case this helps anyone else out - here's the working code: my.zip

    hopefully you won't have to struggle through some last minute coding to get a UDP connection set up via java

Similar Threads

  1. Replies: 2
    Last Post: January 21st, 2014, 09:43 AM
  2. Sending and Receiving Via Tcp And Udp
    By amit1983 in forum Java Theory & Questions
    Replies: 4
    Last Post: December 9th, 2013, 03:56 PM
  3. [SOLVED] Send Hex data in a UDP frame
    By weichsel in forum Java Networking
    Replies: 10
    Last Post: October 29th, 2013, 03:14 PM
  4. Replies: 2
    Last Post: July 9th, 2013, 06:01 PM
  5. Send XML message over UDP?
    By udpkillsme in forum Java Networking
    Replies: 1
    Last Post: June 22nd, 2011, 11:27 AM