Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

Help with a 14 line java proggie!! (Applet)

  • 07-03-2003 11:51PM
    #1
    Registered Users, Registered Users 2 Posts: 683 ✭✭✭


    I got this code from the JDK 1.4 tutorial. The server runs fine (now that I added exception handling), but the client always crashes. Any ideas?
    import java.applet.*;
    import java.awt.*;
    import java.io.*;
    import java.net.*;
    
    public class ChatClientApplet extends Applet
    {
      public void init() {
        String host = getParameter( "host" );
        int port = Integer.parseInt( getParameter( "port" ) );
        setLayout( new BorderLayout() );
        add( "Center", new ChatClient( host, port ) );
      }
    }
    

    the applet takes port address 5555 from the containing html file.

    These are the run-time errors...

    F:\BEDS\java\Murrough\JDK1.4_Turorial\jdk14tut\Chapter2>appletviewer client.html
    java.security.AccessControlException: access denied (java.net.SocketPermission hostname resolve)
    at java.security.AccessControlContext.checkPermission(AccessControlContext.java:270)
    at java.security.AccessController.checkPermission(AccessController.java:401)
    at java.lang.SecurityManager.checkPermission(SecurityManager.java:542)
    at java.lang.SecurityManager.checkConnect(SecurityManager.java:1042)
    at java.net.InetAddress.getAllByName0(InetAddress.java:937)
    at java.net.InetAddress.getAllByName0(InetAddress.java:918)
    at java.net.InetAddress.getAllByName(InetAddress.java:912)
    at java.net.InetAddress.getByName(InetAddress.java:832)
    at java.net.InetSocketAddress.<init>(InetSocketAddress.java:109)
    at java.net.Socket.<init>(Socket.java:119)
    at ChatClient.<init>(ChatClient.java:44)
    at ChatClientApplet.init(ChatClientApplet.java:14)
    at sun.applet.AppletPanel.run(AppletPanel.java:347)
    at java.lang.Thread.run(Thread.java:536)


    Regards,
    merlin_bar


Comments

  • Registered Users, Registered Users 2 Posts: 683 ✭✭✭TenLeftFingers


    Nevermind. I found another example in a different book and it works fine. Just needs modification.


  • Registered Users, Registered Users 2 Posts: 95 ✭✭brainstorm


    im no expert but applets accessing file systems throw up errors like that a lot


  • Registered Users, Registered Users 2 Posts: 68,173 ✭✭✭✭seamus


    Ya. Java was designed with security and modularity in mind - i.e. Applets are supposed to be self-providing, and have very little permission in way of accessing the computer they're running on.

    merlin_bar - if you could post up your solution, or a summary of what you did to get it to work, would be handy if someone else arrived with the same problem :)


  • Registered Users, Registered Users 2 Posts: 683 ✭✭✭TenLeftFingers


    If by file system access you mean the getParamater(String) method; I've always had problems with it.

    I replaced it with
    // make connection
             connection = new Socket( [b]getCodeBase().getHost()[/b], 5555 );
    

    I've progressed a lot in the program so It's very messy at the moment, but it works. I should have it finished tonight, I'll post the whole feckin' lot then. Or a link to it perhaps!

    Regards merlin_bar


  • Registered Users, Registered Users 2 Posts: 683 ✭✭✭TenLeftFingers


    It runs fine with this code. (Both this class and the one in my first post are needed).
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.logging.Logger;
    import java.util.Hashtable;
    
    public class ChatClient extends Panel implements Runnable
    {
    	// Components for the visual display of the chat windows
    	private TextField tf = new TextField();
    	private TextArea ta = new TextArea();
    
    	// The socket connecting us to the server
    	private Socket socket;
    
    	// The streams we communicate to the server; these come
    	// from the socket
    	private OutputStream out;
    	private InputStream in;
    	private boolean acceptID = true;
    
    	private Hashtable codeTable;
    	private Hashtable restoreTable;
    
    	public void initRestoreTable(){
    		restoreTable.put( ".-", "A");
    		//just filled a load of morse code retrieval values
    		restoreTable.put( "...-..-", "$");
    	}
    	public void initHashTable(){
    		codeTable.put("A", ".-");
    		//morse code entry values
    		codeTable.put("$", "...-..-");
    
    		Logger.global.info("Hashtable initialzed.");
    	}
    
    	public ChatClient( String host, int port ) {
    		//set up hashtable
    		codeTable = new Hashtable();
    		restoreTable = new Hashtable();
    		initHashTable();
    		initRestoreTable();
    		// Set up the screen
    		setLayout( new BorderLayout() );
    		add( "North", tf );
    		add( "Center", ta );
    
    		// We want to receive messages when someone types a line
    		// and hits return, using an anonymous class as
    		// a callback
    		tf.addActionListener( new ActionListener() {
    			public void actionPerformed( ActionEvent e ) {
    				processMessage( e.getActionCommand() );
    			}
    		} );
    
    		// Connect to the server
    		try {
    			// Initiate the connection
    			socket = new Socket( host, port );
    			// We got a connection!  Tell the world
    			System.out.println( "connected to "+socket );
    			// Let's grab the streams and create DataInput/Output streams
    			// from them
    			in = socket.getInputStream();
    			out = socket.getOutputStream();
    			// Start a background thread for receiving messages
    			new Thread( this ).start();
    		} catch( IOException ie ) { System.out.println( ie ); }
    	}
    
    	// Gets called when the user types something
    	private void processMessage( String message ) {
    		try {
    			//Convert to morse code
    			String morse = new String();   //To contain converted morse code.
    			String indexedChar = new String();
    
    			for ( int i = 0; i < message.length(); i++){
    				indexedChar = "";
    				indexedChar += message.charAt(i);
    				morse += codeTable.get( indexedChar.toUpperCase() );
    				morse += " ";
    			}
    
    			Logger.global.info(morse);
    
    			// Send it to the server
    			out.write( morse.getBytes() );//was message
    			// Clear out text input field
    			tf.setText( "" );
    			morse = "";//LATEST
    		} catch( IOException ie ) { System.out.println( ie ); }
    	}
    
    	//process recieved message, with header removed.
    	private String revert(String rx){
    		System.out.println("RX=>" +rx);
    		String reverted = "";
    		String tokens[];
    		tokens = rx.split(" ");
    
    		for ( int i = 0; i < tokens.length ; i++){
    			tokens[i].concat(" ");
    			reverted += (String)restoreTable.get(tokens[i]);
    			Logger.global.info("Token[" +i +"] = " +tokens[i] +" returns " +reverted);
    		}
    		return reverted;
    	}
    
    	// Background thread runs this: show messages from other window
    	public void run() {
    		int myID;
    		String myMorseID = "";
    		String header = "";
    		String message = "";
    		String temp = "";
    		try {
    
    			byte buffer[] = new byte[4096];
    			// Receive messages one-by-one, forever
    			while (true) {
    				//Accept ID from server
    				if ( acceptID == true ){
    					int r = in.read( buffer );
    					String id = new String( buffer, 0, r );
    					myID = (int)id.charAt(0);
    					acceptID = false;
    					myMorseID = String.valueOf(myID);
    					myMorseID = (String) codeTable.get(myMorseID);
    					Logger.global.info("myID: " +myID +". myMorseID: " +myMorseID);
    					ta.append("Welcome user " +myID +"\n");
    				}else{
    
    					// Get the next message
    					int r = in.read( buffer );
    					message = new String( buffer, 0, r );
    
    					//evaluate and condition String
    					int headerBreak = message.indexOf(" ");
    
    					try{
    						if(message.length() > 0 && headerBreak != -1){
    							header = message.substring(0, headerBreak);
    							header = header.trim();
    							Logger.global.info("HEADER " +header);
    
    
    
    					if( header.equalsIgnoreCase(myMorseID) ){
    						Logger.global.info("I have been addressed!");
    						//remove header
    						message = message.substring(headerBreak, message.length());
    						message = message.trim();
    						temp = revert(message);
    							ta.append( temp+"\n" );
    					}
    					}
    					}catch(Exception e){Logger.global.info("E");}
    					message = "";
    					header = "";
    					temp ="";
    				}
    			}
    		} catch( IOException ie ) { System.out.println( ie ); }
    	}
    }
    

    Hope this helps. If anyone has a question, feel free to ask. Each client is given an ID on startup. If one client wants to chat to another (lets say 2 wants to talk to 3)...then 2 would type: "3_hello_there" (morse code doesn't support spaces)


  • Advertisement
Advertisement