Hey y'all! I'm fairly new to internet programming, and I'm surrently developping my first socket app in Java.. Now I have a question... I wrote a simple chat client to learn the commands, it uses a datagram socket (that's what I want to stick with for now) and sends/recieves messages.. Everything is functioning perfectly, I'll optimize it as time goes on and use the knowledge forevermore.. But I want to know something, something that I couldn't fund using google...

When you use the command socket.receive(NewPacket); it blocks program execution until an actual socket is received, thus preventing me from doing anything (ie sending a message while waiting for incomming ones).. How do I prevent this? In Visual Basic, I would use the command DoEvents, but what about in Java? Can anybody help me listen for incomming packets without clogging CPU or halting the rest of the program from functioning??? THANK YOU!! Here is my Listen method as-is:

public void ListenForData() {
	// Recieve data

	while (true) {
		byte[] rcvm = new byte[MAXDATA];
		DatagramPacket NewPacket = new DatagramPacket(rcvm, rcvm.length);
		try {
			DGS.receive(NewPacket);
		} catch (Exception ex) {
			continue;
		}
		txtRecieved.append("Message from " + NewPacket.getAddress()
			+ ": " + new String(NewPacket.getData()) + "\n");
	}

}

Also, I am not too sure about exeception handelling here so if I can't do it with continue please let me know.

:cheesy:

I answered my own question.. Ever hear of muti-threading and sub-classing?? well I did that lol, and learned something new.. Here's basically how I have it set up now:

This sub-class is within my main class:

public class Listener extends Thread {
    	public Listener() {
    		// NOTHING
    	}
    	public void run () {
	    	// Recieve data
			while (true) {
				byte[] rcvm = new byte[MAXDATA];
				DatagramPacket NewPacket = new DatagramPacket(rcvm, rcvm.length);
				try {
					DGS.receive(NewPacket);
				} catch (Exception ex) {
					// IGNORE
				}
				if (!(NewPacket.getAddress() == null))
				txtRecieved.append("Message from " + NewPacket.getAddress()
					+ ": " + new String(NewPacket.getData()) + "\n");
			}
    	}
    }

I call it using new Listener().start(); and it runs in the background not disturbing my app at all! YAY!! Now to find someone to test it with to make sure it works fine.. Unfortunately I can't send a message to myself and if I do nothing happens, I guess because I'm using Datagram t never gets back to me becasue my socket is currently busy sending the data.. so..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.