InetAddress stored in hashtable

  • (2 Pages)
  • +
  • 1
  • 2

19 Replies - 1977 Views - Last Post: 19 May 2012 - 07:20 AM Rate Topic: -----

#1 gliddon   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 57
  • Joined: 06-October 11

InetAddress stored in hashtable

Posted 15 May 2012 - 08:45 PM

I'm stuck at what should probably be the very last step in my program and I can't figure out what to do.
I have a hashtable storinga list of computer names and ip addresses in a LAN.

basically what happens is a JList displays the names, you click on the one you want, and in the listener there is a call to messenger class which takes an InetAddress as a parameter (to make connections to remote host).

Anyway, my problem is that the address in the hashtable is being stored as an object, kind of generically I suppose.
I keep trying to find a way to get the value of the hashtable as an InetAddress to send to the other class.
Can anyone see what I'm doing wrong here?

truncated code
public void valueChanged(ListSelectionEvent le)
		{
       		String selection = (String) userList.getSelectedValue(); //gets selected list cell as string(hostname
       			System.out.println("Current selection: " + clientList.get(selection));
       		try
       		{
       			InetAddress sendTo = clientList.get(selection) ; //HELP ME HERE PLEASE.. 
       			Messenger messenger = new Messenger(sendTo);
       		}
       		catch(IOException ioException)
       		{
       			displayMessage("Error resolving client address");
       		}
    	}



I'm going to keep looking but if anyone can help you'll save my life right now.
Thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: InetAddress stored in hashtable

#2 Martyr2   User is offline

  • Programming Theoretician
  • member icon

Reputation: 5612
  • View blog
  • Posts: 14,686
  • Joined: 18-April 07

Re: InetAddress stored in hashtable

Posted 15 May 2012 - 09:24 PM

Well if you stashed it in the clientList in InetAddress form, you can simply cast it back when you take it out. So if you did something like...

InetAddress blah = new InetAddress();
clientList.put("someaddy",blah);



Then all you need to do is cast it back to InetAddress on its way out...

InetAddress sendTo = (InetAddress)clientList.get("someaddy");



See how we put "InetAddress" in parenthesis? We are taking the object out of the hash table, casting it back to its original class type.

Note: This assumes you again stored the object from its InetAddress form earlier and are sure that you don't have any other object types in the hash table.

:)
Was This Post Helpful? 0
  • +
  • -

#3 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3744
  • View blog
  • Posts: 17,121
  • Joined: 20-September 08

Re: InetAddress stored in hashtable

Posted 16 May 2012 - 08:03 AM

Unless forced by using an old version of Java, you should be using Map<String, InetAddress>,normally as a HashMap
Was This Post Helpful? 0
  • +
  • -

#4 gliddon   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 57
  • Joined: 06-October 11

Re: InetAddress stored in hashtable

Posted 16 May 2012 - 06:59 PM

Wanted to say thanks for the bit about the cast. I tried doing that before but must have typod somewhere, and I wasn't positive that it would work, long story short that is working now.

I will look into the hashmap as I saw some things saying a similar thing a while after I had implemented the hashtable.

For some reason I am having my messenger class crash on me and I'm not positive why, but suspect it has something to do with the InetAddress from above.

Basically the client class has a JList with an action listener which calls an instance of the messenger class with the InetAddress (the exact one we cast in the above.)

Since you guys were so helpful can you see any reason that the address would not be working correctly, or maybe something I'm missing as to why it won't run yet? The gui doesn't even load (messenger class).

any thoughts?

import sun.net.*;
import java.net.*;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingUtilities;

public class Messenger extends JFrame
{
	private JTextArea displayArea;
	private JTextField inputField;
	private InetAddress toAddress;

	public Messenger()
	{
	}

    public Messenger(InetAddress address)
    {
    	JFrame window = new JFrame("Messenger");
    	displayArea = new JTextArea();
    	inputField = new JTextField();
    	String input = "";

    	window.add(displayArea,BorderLayout.CENTER);
    	window.add(inputField,BorderLayout.SOUTH);
    	window.setVisible(true);
    	runMessenger();

    	Runnable r = new ReceiveThread();
		new Thread(r).start();
	}	//end constructor

	public void runMessenger()
	{
		SwingUtilities.invokeLater
		(
        	new Runnable()
        	{
            	public void run() // updates displayArea
            	{
					inputField.addActionListener(new ActionListener()
					{
						public void actionPerformed( ActionEvent event )
						{
							final String input = inputField.getText();
							displayMessage(input);
						try
    						{
    							int port = 5010;
    							DatagramSocket sendSocket = new DatagramSocket(port);
								byte[] data = input.getBytes();
								DatagramPacket packet = new DatagramPacket(data, data.length, toAddress, 5012);	// Create a DatagramPacket ADDRESS PACKET TO SERVER!!!
								sendSocket.send(packet);
    							sendSocket.close();
    						}
    						catch(IOException ioException)
							{
								displayMessage("Error sending message::");
					    	}
							}
					});

				}
			}
		);
	}
	public void displayMessage( final String messageToDisplay )
   	{
      SwingUtilities.invokeLater(
         new Runnable()
         {
            public void run() // updates displayArea
            {
               displayArea.append( messageToDisplay );
            } // end method run
         }  // end anonymous inner class
      ); // end call to SwingUtilities.invokeLater
   	} // end method displayMessage
}	//end class




here's the runnable

import sun.net.*;
import java.net.*;
import java.io.*;

public class ReceiveThread extends Messenger implements Runnable{

	public void run()
	{
		int port = 5012;
		while ( true )
	    {
         	try // receive packet and display contents
		    {
		        DatagramSocket receiveSocket = new DatagramSocket(port);
        		byte[] data = new byte[ 100 ]; // set up packet
		        DatagramPacket receivePacket = new DatagramPacket(data, data.length );
		        receiveSocket.receive( receivePacket ); // wait for packet

        		// display packet contents
		        displayMessage( "\nPacket received:" + "\nFrom host: " + receivePacket.getAddress() + "\nHost port: " + receivePacket.getPort() + "\nLength: " + receivePacket.getLength() +
	            "\nContaining:\n\t" + new String( receivePacket.getData(), 0, receivePacket.getLength() ) );
				displayMessage(new String( receivePacket.getData() ));

            	receiveSocket.close();
		    } // end try
        	catch ( IOException exception )
			{
				displayMessage( exception + "\n" );
				exception.printStackTrace();
	      	} // end catch
     	} // end while
	}	//end run()
}	//end class



Thanks again!!
Was This Post Helpful? 0
  • +
  • -

#5 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8381
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: InetAddress stored in hashtable

Posted 16 May 2012 - 07:12 PM

View Postgliddon, on 16 May 2012 - 09:59 PM, said:

For some reason I am having my messenger class crash on me and I'm not positive why,

Post the stack trace
Was This Post Helpful? 0
  • +
  • -

#6 gliddon   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 57
  • Joined: 06-October 11

Re: InetAddress stored in hashtable

Posted 16 May 2012 - 07:32 PM

I would but it is infinitely looping an exception, which makes me think it doesn't reach the try catch.
PS it does that on the machine running the server and the client, and the machine running just the client
Was This Post Helpful? 0
  • +
  • -

#7 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8381
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: InetAddress stored in hashtable

Posted 16 May 2012 - 07:36 PM

View Postgliddon, on 16 May 2012 - 10:32 PM, said:

I would but it is infinitely looping an exception, which makes me think it doesn't reach the try catch.

So ? Which Exception at which line ?

Quote

PS it does that on the machine running the server and the client, and the machine running just the client

Don't really care. You should know which code you are running. And that code generates a stack trace. That is what you need
Was This Post Helpful? 0
  • +
  • -

#8 gliddon   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 57
  • Joined: 06-October 11

Re: InetAddress stored in hashtable

Posted 16 May 2012 - 08:05 PM

ok, I had to change the code a bit just to get a stack, but now I'm getting a bind Exception because I changed the port from the receive thread to 5013, it was 5012 before, the same port that the client uses to send from. (if I am correct)
Note I only made those changes so that I could get a trace at all as it was simply printing and endless loop far too fast to get

Something is wrong with the address.. format.. I dunno. Not for sure, just my feeling.

anyway here's the trace

Starting Client
[email protected]@ table:::
{Stacy-PC=/192.168.1.37}
Current selection: /192.168.1.37
Current selection: /192.168.1.37
java.net.BindException: Address already in use: Cannot bind
at java.net.DualStackPlainDatagramSocketImpl.socketBind(Native Method)
at java.net.DualStackPlainDatagramSocketImpl.bind0(DualStackPlainDatagra
mSocketImpl.java:65)
at java.net.AbstractPlainDatagramSocketImpl.bind(AbstractPlainDatagramSo
cketImpl.java:95)
at java.net.DatagramSocket.bind(DatagramSocket.java:376)
at java.net.DatagramSocket.<init>(DatagramSocket.java:231)
at java.net.DatagramSocket.<init>(DatagramSocket.java:284)
at java.net.DatagramSocket.<init>(DatagramSocket.java:256)
at ReceiveThread.run(ReceiveThread.java:23)
at java.lang.Thread.run(Thread.java:722)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Messenger$2.run(Messenger.java:102)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:701)
at java.awt.EventQueue.access$000(EventQueue.java:102)
at java.awt.EventQueue$3.run(EventQueue.java:662)
at java.awt.EventQueue$3.run(EventQueue.java:660)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDo
main.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:671)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre
ad.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.
java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
ad.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
Was This Post Helpful? 0
  • +
  • -

#9 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8381
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: InetAddress stored in hashtable

Posted 16 May 2012 - 08:10 PM

java.net.BindException: Address already in use: Cannot bind

What else do you want ? Here is your error
Was This Post Helpful? 0
  • +
  • -

#10 gliddon   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 57
  • Joined: 06-October 11

Re: InetAddress stored in hashtable

Posted 16 May 2012 - 08:17 PM

right, as in change the port.. however I just changed the port to 9000 and now I'm getting this

Starting Client
[email protected]@ table:::
{Stacy-PC=/192.168.1.37}
Current selection: /192.168.1.37
Current selection: /192.168.1.37
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Messenger$2.run(Messenger.java:102)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:701)
at java.awt.EventQueue.access$000(EventQueue.java:102)
at java.awt.EventQueue$3.run(EventQueue.java:662)
at java.awt.EventQueue$3.run(EventQueue.java:660)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDo
main.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:671)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre
ad.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.
java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
ad.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
java.net.BindException: Address already in use: Cannot bind
at java.net.DualStackPlainDatagramSocketImpl.socketBind(Native Method)
at java.net.DualStackPlainDatagramSocketImpl.bind0(DualStackPlainDatagra
mSocketImpl.java:65)
at java.net.AbstractPlainDatagramSocketImpl.bind(AbstractPlainDatagramSo
cketImpl.java:95)
at java.net.DatagramSocket.bind(DatagramSocket.java:376)
at java.net.DatagramSocket.<init>(DatagramSocket.java:231)
at java.net.DatagramSocket.<init>(DatagramSocket.java:284)
at java.net.DatagramSocket.<init>(DatagramSocket.java:256)
at ReceiveThread.run(ReceiveThread.java:23)
at java.lang.Thread.run(Thread.java:722)
Was This Post Helpful? 0
  • +
  • -

#11 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8381
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: InetAddress stored in hashtable

Posted 16 May 2012 - 08:30 PM

Your posted Messenfer class has only 80 lines but obviously in that class

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Messenger$2.run(Messenger.java:102)

in the run() method at line 102 you have a null pointer Exception

Should be easy figurint out (add a println() if required) which Object is null
Was This Post Helpful? 0
  • +
  • -

#12 gliddon   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 57
  • Joined: 06-October 11

Re: InetAddress stored in hashtable

Posted 16 May 2012 - 08:47 PM

102 is the displayMessage append statement, (appends the textArea with the messge)
Was This Post Helpful? 0
  • +
  • -

#13 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8381
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: InetAddress stored in hashtable

Posted 17 May 2012 - 03:50 PM

	public void displayMessage( final String messageToDisplay )
   	{
            SwingUtilities.invokeLater(
            new Runnable()
            {
                 public void run() // updates displayArea
            {
               displayArea.append( messageToDisplay );
            } // end method run
         }  // end anonymous inner class
      ); // end call to SwingUtilities.invokeLater
   	} // end method displayMessage


Fow which obscure reason do you start a Thread to simply append a String to a JTextArea ?
First JTextArea are not thread safe and creating a runnable object in another thread that is invoke later will grab a lot more resource than simply

displayArea.append( messageToDisplay );

displayMessage() is already called by a thread. Don't start a new thread in in it and make it synchronized as multiple thread may call it at the same time.

Actually, looking down in your stack, why is runMessenger in a thread so start with ?
Was This Post Helpful? 0
  • +
  • -

#14 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3744
  • View blog
  • Posts: 17,121
  • Joined: 20-September 08

Re: InetAddress stored in hashtable

Posted 17 May 2012 - 04:53 PM

That's actually the correct way to update a text component from a thread that's not the EDT. Generally speaking, you should always do it that way, there are couple of exceptions, but it's actually always safer to assume there are no exceptions.
Was This Post Helpful? 0
  • +
  • -

#15 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8381
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: InetAddress stored in hashtable

Posted 17 May 2012 - 05:01 PM

It is called by the actionPerformed() so in the EDT thread :)
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2