How do I bind a UDP socket to a port and read from a server in Java?

  • Java
  • Thread starter sean_vn
  • Start date
  • Tags
    Java System
In summary: OfAtoms = tokenizer.nextToken().getInt();symbols = tokenizer.nextToken().getStringArray();inputX = tokenizer.nextToken().getFloatArray();inputY = tokenizer.nextToken().getFloatArray();inputZ = tokenizer.nextToken().getFloatArray();}}}In summary, Sean O'Connor is using a Java native wrapper for his fast Walsh Hadamard transform and O'Connor Transform code. He is getting 2000 65536-point WHT's per second and 540 65536-point OCT's per second. That is about as fast as you will get without
  • #1
sean_vn
1
0
I have just created a Java native wrapper for my fast Walsh Hadamard transform and O'Connor Transform code. I am getting 2000 65536-point WHT's per second and 540 65536-point OCT's per second. That is about as fast as you will get without resorting to Nvidia CUDA or whatever.
The code is here:
http://code.google.com/p/lemontree/downloads/list"
The OCT transforms arbitrary numerical data into data with a Gaussian distribution. It has many uses for compressive sensing, neural nets and genetic algorithms.
Have fun and be good,
Sean O'Connor
 
Last edited by a moderator:
Technology news on Phys.org
  • #2
Ok, so I need a hand with using loaders. I want to know where to put a loader file if I want to use it in JAVA 3d. this will be my first program in Java3d. I am relatively new to in depth java, and have a lot of modeling experience. If I can load my models into the J3d enviornment, it will make it way easier for me to teach myself because I can manipulate my own models.

With that said, I only need the following answered-

Once I install JAVA3d, it installs in a separate folder than the JDK I am currently working with. Are those libraries automatically reconized by my JDK, or do I have to do soem work and reference it's location somewhere in my tools (I'm using EDITPLUS 3).

Where do I put my Loader? I am using the milkshape "MS3DLoader-1.0.8.jar" loader.

Also, I have the code here, but the thing is, I'm not 100% sure where to put in the name of my model, "BOB". I think its at the bottom, where it says "raptor.ms3d". the model will currently be in the same folder as the class we are programming here.

Setup:

import com.sun.j3d.loaders.*;
import com.glyphein.j3d.loaders.milkshape.MS3DLoader;

Loader loader = new MS3DLoader(MS3DLoader.LOAD_ALL);

Loading a model from a URL:

com.sun.j3d.loaders.Scene scene = loader.load(url);
BranchGroup group = scene.getSceneGroup();

Loading a model from a file:

java.io.File file = new java.io.File("raptor.ms3d");
if (file.getParent().length() > 0) // figure out the base path
loader.setBasePath(file.getParent() + java.io.File.separator);
Scene scene = loader.load(file.getName());
BranchGroup group = scene.getSceneGroup();
 
  • #3
So basically i am developing a molecular viewer in java with opengl bindings (JOGL) and i am having problems with creating an importFile() method. This method will be responsible for importing all the data from .xyz (mol) files. It is a crucial point because the whole 3D Opengl part will rely on the data imported by this method.
153

Si -8.2202000000 -5.6491900000 -1.5237200000
Si -7.3205700000 -7.6948600000 -0.7860500000
Si -6.3849500000 -3.8557600000 -4.4003200000
Si -6.3816400000 -5.7792300000 -3.0557700000
Si -4.4540900000 -1.9259100000 -7.0791000000

Here is an example from an .xyz file which contains the number of atoms at the top, then there comes the symbol of each atoms and the x, y, z, coordinates for each atoms of the molecules. OpenGl will create a sphere for each atom in the xyz files and the bonds by the Van der Waals radius values .
I want to import them for easy usage with OpenGL and to create a basic default table model in java to show the imported data separately.

I tried to do this method already but without any success.
Somehow all the coordinates and symbols should be stored in an array which can be accessed by OpenGL and the table.
I would really appreciate that if someone could help me with a bit of code or advice how i should implement it.

I don't want to stick to this way of import because i think it is not the best one but looked quite easy at first (i mean with tokenizer) so please share your ideas and codes about this
Code:
public void importFile() throws IOException
{
		//the selected file
		File fileSelected;
		//filenamextensionfilter
		FileNameExtensionFilter fileFilter;
		//create filechooser
		JFileChooser fileChooser = new JFileChooser();
		//arraylist of fileNames
		 ArrayList<String> fileNames = new ArrayList<String>();
		//the bufferedreader for importfile method
		BufferedReader inputFile;
		fileFilter = new FileNameExtensionFilter("XYZ", "xyz");
		fileChooser.setFileFilter(fileFilter);
		
		int returnVal = fileChooser.showOpenDialog(fileChooser);
		
		double numberOfAtoms;
		String [] symbols = null;
		Float [] inputX = null;
		Float [] inputY = null;
		Float [] inputZ = null;
		
		if(returnVal == JFileChooser.APPROVE_OPTION)
		{
			fileSelected = fileChooser.getSelectedFile();
			String[] fileName = fileSelected.getName().split("\\.");
			if(fileNames.contains(fileName))
			{
				int i = fileNames.indexOf(fileName);
				fileNames.remove(i);
			}
			inputFile = new BufferedReader(new FileReader(fileSelected));
			
			int counter = 0;
			
			StreamTokenizer tokenizer = new StreamTokenizer(inputFile);
			
			//INPUTTING
		  	if (tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {
                                      throw new IOException("Could not understand format : " 
                                       + tokenizer);
                         } else {
                            numberOfAtoms = tokenizer.nval;
                         } // end if
			
			// skip next line  
    		         inputFile.readLine();
    		
			try {
				
			for(int i=0; i< numberOfAtoms; i++) {                
                           // a set of four tokens constitute the atom 
				
				//  d) the symbol  
				if (tokenizer.nextToken() != StreamTokenizer.TT_WORD) {
                                         throw new IOException("Could not understand format : " 
                                           + tokenizer);
                                } else {
                	                  int j = 0;
                                          symbols[j] = tokenizer.sval.toLowerCase();
                                           j++;
                                } // end if
                                 //  a) the x coordinate               
                               if (tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {
                                          throw new IOException("Could not understand format : " 
                                           + tokenizer);
                               } else {
                	         int j = 0;
                                 inputX[j] = (float) tokenizer.nval;
                                   j++;
                               } // end if
                
                                 //  b) the y coordinate               
                               if (tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {
                                      throw new IOException("Could not understand format : " 
                                           + tokenizer);
                               } else {
                                        int j = 0;
					inputY[j] = (float) tokenizer.nval;
                                        j++;
                               } // end if
                
                                 //  c) the z coordinate               
                               if (tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {
                                         throw new IOException("Could not understand format : " 
                                           + tokenizer);
                                 } else {
                	                int j = 0;
					inputZ[j] = (float) tokenizer.nval;
                                          j++;
                                 } // end if
                
                                 // and now we can safely add this atom to our list
                                //molecule.addAtom(symbol, x, y, z, i);
                
                                // skip to next line
                                 inputFile.readLine();
                                 tokenizer = new StreamTokenizer(inputFile);
                                  } // end for
                               } catch (Exception e) {
                                    throw new IOException("Error reading file : " + tokenizer
                                  + "\n Exception is : " + e.toString());
                             } // end of try .. catch block
			
		//TEST
		System.out.println(numberOfAtoms+ " " + inputX[0] + " " + inputY[0] + " " +inputZ[0] + " "+ symbols[0]);
        // return the "raw" molecule
        return;  
				
			
		}
	}
 
  • #4
Hi,

I'm trying to get familiar with the system clipboard by building a "clipboard listener" what I want to do is listen to the clipboard and when it changed print the new value that is put into the clipboard[if it is text].

This is what I tried:

Code:
import java.awt.Toolkit;  
import java.awt.datatransfer.*;  
import java.io.IOException;  
  
public class ClipboardListener extends Thread implements ClipboardOwner {  
      
    Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();  
      
    public void run(){  
        Transferable selection = systemClipboard.getContents(this);  
        gainOwnership(selection);  
        System.out.println("listening");  
    }  
      
    public void gainOwnership(Transferable t){  
        System.out.println("gain ownership");  
        systemClipboard.setContents(t, this);  
    }  
      
    public void lostOwnership(Clipboard clipboard, Transferable contents) {  
        System.out.println("lost ownership");  
        if (contents.isDataFlavorSupported(DataFlavor.stringFlavor)){  
                System.out.println((string) contents.getTransferData(DataFlavor.stringFlavor));  
        }  
        gainOwnership(contents);  
    }  
}

Code:
public class myApp {
	

	public static void main(String[] args){
		ClipboardListener listener = new ClipboardListener();
		listener.start();
		while(true){}
	}

}

Now 2 strange things happen:
1. lostOwnership never runs if I run the code in Mac OS X [it does if I run it in Windows 7].
2. From some reason I get an exception while I'm trying to print what has changed within the clipboard, in lostOwnership.
 
Last edited:
  • #5
Javascript is in an external file liked by this:
<script type="text/javascript" src="myscript.js"></script>
in the head tag

i have
<form name="myform" action="" method="POST" onSumbit="return validateForms()">
and some form stuff and then:
<input type="submit" value="Submit" onclick="calculate()" />

in the javascript function i have this,


function validateForms(){
alert("form will be checked");

var x=document.forms[myform]["firstname"].va…
if (x==null || x==""){
alert("First name must be filled out");
return false;
}
}

WHY THE HECK IS THIS NOT WORKING!
 
  • #6
Dear all,

I have been facing a persisting problem in Java3D graphic. The problem can be summarized into the following:

I have a QuadArray and want to show both the quads and the edges. Since I can't find a way to show both ( I am not sure it is possible), I have set up a LineaArray for the edges so that I can show the quads and the LineArray as the edges. The problem is that the lines overlap with the Quads and this makes the lines look broken and sometimes invisible.

Can anybody help me out?

Thanks
 
  • #7
I need some guidance on how to Bind a UDP socket to a port and then read from server.

The server is already done I just need help with the client here is what I have so far.One more thing, I don't know if I am using the ports right, 49009 is the server port and 12000 is the client port. I think I have all of them in the right place but if I don't will you correct me, thank you.
Code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;public class UDPClient
{

	public static void main(String[] args) throws Exception
	{
		// read some input from user
		BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
		
		// create a udp socket 
		DatagramSocket clientSocket = new DatagramSocket();
		InetAddress IPAddress = InetAddress.getLocalHost();
		
		byte[] receiveData = new byte[1024];
		byte[] sendData = new byte[1024];
      
      //Creating a listening socket from local port
      DatagramSocket listeningSocket = new DatagramSocket(12000);
		
		// Specifying data request and port
		String sentence = "DATA REQUEST:12000";
		sendData = sentence.getBytes();
		
		DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 49009);
		clientSocket.send(sendPacket);
      
      
		
		DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
		listeningSocket.receive(receivePacket);
		
		String modifiedSentence = new String(receivePacket.getData());
		
		System.out.println(modifiedSentence);

		clientSocket.close();
      listeningSocket.close();
      
		
	}

}
 
Last edited:

What is the system clipboard in Java?

The system clipboard in Java is a temporary storage space that allows data to be transferred between different applications or within the same application. It is a part of the operating system and can hold different types of data such as text, images, and files.

How do I access the system clipboard in Java?

To access the system clipboard in Java, you can use the java.awt.datatransfer.Clipboard class. This class provides methods to get and set data on the clipboard. You can also use the java.awt.Toolkit class to get the default system clipboard.

Can I put data on the system clipboard in Java?

Yes, you can put data on the system clipboard in Java using the setContents() method of the java.awt.datatransfer.Clipboard class. This method takes in a Transferable object, which can hold different types of data, and puts it on the clipboard.

How do I get data from the system clipboard in Java?

To get data from the system clipboard in Java, you can use the getContents() method of the java.awt.datatransfer.Clipboard class. This method returns a Transferable object, from which you can extract the data using the getTransferData() method.

What are some common data formats supported by the system clipboard in Java?

The system clipboard in Java supports various data formats such as plain text, HTML, images, and files. It also supports custom data formats that can be registered using the setContents() method. A complete list of supported data formats can be found in the DataFlavor class.

Back
Top