Getting ConnectException in linux with Hello World socket program

Hello
i'm running a hello world application that uses sockets ( [found here|http://blog.taragana.com/index.php/archive/understanding-java-simplified-hello-world-for-socket-programming/] ) . I'm running it using a windows machine and a linux machine. When the windows machine is the server, and linux the client, no problem, the application works fine. But when the server is linux and the client is in windows i got a
java.net.ConnectException: Connection timed out: connect
     at java.net.PlainSocketImpl.socketConnect(Native Method)
     at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:352)
in the linux machine i've checked the port being used and it seems to be listening
logan@logan-desktop:~$ netstat --listening |grep 6500
tcp6 0 0 [::]:6500 [::]:* LISTEN
i've also tried changing the port and i got the same error
and i have to say that there is no firewall installed in the linux machine and in the windows machine i disabled the firewall but i'm still getting the same error
what else should i check? or any clue about what could be happening?
thank you in advance
any help would be appreciated

puki_el_pagano wrote:
i'm running a hello world application that uses sockets ( [found here|http://blog.taragana.com/index.php/archive/understanding-java-simplified-hello-world-for-socket-programming/] ) . I'm running it using a windows machine and a linux machine. When the windows machine is the server, and linux the client, no problem, the application works fine. But when the server is linux and the client is in windows i got a
java.net.ConnectException: Connection timed out: connect
     at java.net.PlainSocketImpl.socketConnect(Native Method)
     at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:352)
in the linux machine i've checked the port being used and it seems to be listening
logan@logan-desktop:~$ netstat --listening |grep 6500
tcp6 0 0 [::]:6500 [::]:* LISTEN
i've also tried changing the port and i got the same error
and i have to say that there is no firewall installed in the linux machine Are you absolutely sure?
what else should i check? On the windows box
open a cmd window
C:> telnet linuxbox 6500

Similar Messages

  • Having trouble with Hello World web applet...

    I used this tutorial,
    http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter01/simpleApplet.html
    However, I STILL get a red X on my personal webpage even after compiling everything here.. Another weird thing was, I couldn't even compile it correctly without removing the 'public' before the 'class'.
    Heres my code
    class HelloWorld extends java.applet.Applet
       public void paint(java.awt.Graphics g)
            g.drawString("Hello World!",50,25);
            System.out.println("Hello World!");
    } HTML:
    <applet code="HelloWorld.class" width="150" height="50"></applet>And the error I get.
    load: HelloWorld.class is not public or has no public constructor.
    java.lang.IllegalAccessException: Class sun.applet.AppletPanel can not access a member of class HelloWorld with modifiers ""
         at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
         at java.lang.Class.newInstance0(Unknown Source)
         at java.lang.Class.newInstance(Unknown Source)
         at sun.applet.AppletPanel.createApplet(Unknown Source)
         at sun.plugin.AppletViewer.createApplet(Unknown Source)
         at sun.applet.AppletPanel.runLoader(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)Somebody help me please?

    Oh wait, the java file needed the same name as the class...
    Getting the same problem still:
    oad: HelloWorld.class is not public or has no public constructor.
    java.lang.IllegalAccessException: Class sun.applet.AppletPanel can not access a member of class HelloWorld with modifiers ""
         at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
         at java.lang.Class.newInstance0(Unknown Source)
         at java.lang.Class.newInstance(Unknown Source)
         at sun.applet.AppletPanel.createApplet(Unknown Source)
         at sun.plugin.AppletViewer.createApplet(Unknown Source)
         at sun.applet.AppletPanel.runLoader(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    public class HelloWorld extends java.applet.Applet
       public void paint(java.awt.Graphics g)
            g.drawString("Hello World!",50,25);
            System.out.println("Hello World!");
    null

  • Problem with "Hello World"  program

    i am new to java.
    i have recently installed java and the version is :
    E:\>java -showversion
    java version "1.6.0_06"
    Java(TM) SE Runtime Environment (build 1.6.0_06-b02)
    Java HotSpot(TM) Client VM (build 10.0-b22, mixed mode, sharing)
    First.java_
    class First
    public static void main (String[] args)
    System.out.println("Hello World!");
    My "First.java" compiles fine.
    but,when i execute it, i got the following Error:
    E:\>javac First.java
    E:\>java First
    Exception in thread "main" java.lang.NoClassDefFoundError: First
    Caused by: java.lang.ClassNotFoundException: First
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    i need assistance..

    As stated in the [thread earlier today|http://forum.java.sun.com/thread.jspa?threadID=5304111&tstart=0], you need to specify the classpath like this:
    java -cp . First(Note that there is a period between the -cp and First with spaces separating the period from the -cp and the First).

  • Problem in getting data into database with standard direct input program

    HI All,
    I am having problem which is not updating the records in MM01 or MM02 with standard direct input program. i have data in internal table. from that table i am trying to upload into database by using background job MRP_MATERIAL_MASTER_DATA_LOAD.
    when i execute my program it is showing message job is started. then i go into sm37 and seethe job status by executing. there also i am seeing job completed succesfully.
    but if i go to mm03 and find the materials are updated or created there i couldn't find the material numbers which are from internal table.
    So if ny one help me it wil be great.
    Thanks in Advance
    Venkat N

    Hi Anil,
    Thanks for your answer, but i am facing problem is i have material no and denominator and Actual UOM and nominator field values in the flat file.....
    by using RMDATIND direct input program with MRP_MATERIAL_UPLOAD as job name for background job while uploading data into database.
    here i am not getting data in to database, but when i execute the job in sm37 it is showing that message job processing successfully completed...this is my status..
    if u can help me in this it will be gr8ful..
    Thanks,
    Venkat N

  • How to control tcp connection with java tcp socket programing ??

    Hi,
    I am connecting a server as using java socket programming.
    When server close the connection (socket object) as using close() method ,
    I can not detect this and My program continue sending data as if there is a connection with server.
    How to catch the closing connection ( socket ) with java socket programming.
    My Client program is as following :
    import java.io.PrintWriter;
    import java.net.Socket;
    public class client
      public client()
       * @param args
      public static void main(String[] args)
        Socket socket=null;
        PrintWriter pw=null;
        try
                          socket = new Socket("localhost",5555);
                          pw = new PrintWriter(socket.getOutputStream(),true);
                          int i=0;
                          while (true)
                            i++;
                            pw.println(i+". message is being send.");
                            Thread.sleep(5000);
        } catch (Exception ex)
                          ex.printStackTrace();
        } finally
                          try
                            if(pw!=null)pw.close();
                            if(socket!=null)socket.close();
                          } catch (Exception ex)
                            ex.printStackTrace();
                          } finally
    }

    I changed the code as following. But I couldn't catch the EOFException when I read from the socket. How can I catch this exception ?
    import java.io.BufferedReader;
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class client
      public client()
       * @param args
      public static void main(String[] args)
        Socket socket=null;
        PrintWriter pw=null;
        BufferedReader bufIn=null;
        InputStreamReader inRead=null;
        InputStream in=null;
        try
                          socket = new Socket("localhost",5555);
                          in = socket.getInputStream();
                          inRead = new InputStreamReader(in);
                          bufIn = new BufferedReader(inRead);
                          pw = new PrintWriter(socket.getOutputStream(),true);
                          int i=0;
                          while (true)
                            i++;
                            try
                              bufIn.readLine();
                              pw.println(i+". message is being send.");
                              System.out.println(i+". message has been send");
                            } catch (Exception ex2)
                              System.out.println(ex2.toString());
                              System.out.println(i+". message could not be send");
                            } finally
                            Thread.sleep(5000);
        } catch (EOFException ex)
                          ex.printStackTrace();
        } catch (InterruptedException ex)
                          ex.printStackTrace();
        } catch (IOException ex)
                          ex.printStackTrace();
        } finally
                          try
                            if(pw!=null)pw.close();
                            if(socket!=null)socket.close();
                          } catch (Exception ex)
                            ex.printStackTrace();
                          } finally
    }

  • Help needed with swings for socket Programming

    Im working on a Project for my MScIT on Distributed Computing...which involves socket programming(UDP)....im working on some algorithms like Token Ring, Message Passing interface, Byzantine, Clock Syncronisation...i hav almost finished working on these algorithms...but now i wanna give a good look to my programs..using swings but im very new to swings...so can anyone help me with some examples involving swings with socket programming...any reference...any help would be appreciated...please help im running out of time..
    thanking u in advance
    anDy

    hi im Anand(AnDY),
    i hav lost my AnDY account..plz reply to this topic keeping me in mind :p

  • PROBLEM WITH HELLO WORLD FILE IN JAVA!!! PLZ ASSIST ME, THE NEWBIE! THNX!!

    This is horrible, I get this new Java programming book and my computer isn't working with the files. #1: The *.java files appear not as the little java character, but as a notepad file that says it's a java type file, I saved it correctly too. #2: Also, when I made it a class file, the class file appears as a white paper with little icons on it (u usually get this when you've got an unknown file on your hands. This file also says in the subtext that it is the correct file-type ".class". #3: Okay, now I've gotten to the part where I am trying to run the program in DOS, but when I attempt this by typing "java Hello"and hit enter, DOS replies with "Exception in thread "main" java.lang.NoClassDefFoundError: hello". Please help me out! Thanks!!

    Start with the second link. Follow the directions exactly. Uninstall and reinstall Java if necessary.
    Sun's basic Java tutorial
    START HERE
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java.

  • Has anyone been able to get Forte on Linux with j2sdk1.4.0

    I am noticing a trend in the posts from people asking questions about setting up Forte on Linux. (1) Setting the JDK_HOME doesn't seem to work too well; (2) replies tend to reference old URL's or the vague URL's provided by SUN; (3) if not (2) then no reply at all.
    I was able to get Forte working with the JDK1.3.1, but setting JAVA_HOME with the sdk doesn't work with the same approach.
    Any ideas?
    Solution may be:
    If replies = 0 then JBuilder;

    I have my own solution. Jedit.

  • Need help with java.nio.socket program.

    Can someone please help me here? I am trying to create a class that listens on a socket for an incoming connection, but I am getting the following error on compile:
    SocketIn.java:48: incompatible types
    found : java.nio.channels.SocketChannel
    required: java.net.Socket
    Socket requestSocket = requestChannel.accept();
    Here is my code:
    package NETC;
    import java.net.*;
    import java.util.*;
    import java.io.*;
    import java.nio.*;
    import java.nio.charset.*;
    import java.nio.channels.*;
    import java.nio.channels.spi.*;
    public class SocketIn{
         // Buffer for any incoming data.
         private static ByteBuffer inBuffer = ByteBuffer.allocateDirect(1024);
         CharBuffer charBuffer = null;
         public SocketIn(int intPort)throws Exception{
              // Create a non-blocking server socket.
              ServerSocketChannel serverChannel = ServerSocketChannel.open();
              serverChannel.configureBlocking(false);
              // Use the host and port to bind the server socket.
              InetAddress inetAddress = InetAddress.getLocalHost();
              InetSocketAddress socketAddress = new InetSocketAddress(inetAddress, intPort);
              serverChannel.socket().bind(socketAddress);
              // The selector for incoming requests.
              Selector requestSelector = SelectorProvider.provider().openSelector();
              // Put the server socket on the selectors 'ready list'.
              serverChannel.register(requestSelector, SelectionKey.OP_ACCEPT);
              while(requestSelector.select() > 0){
                   System.out.println("Connection Accepted...");
                   // A request has been made and is ready for IO.
                   Set requestKeys = requestSelector.selectedKeys();
                   Iterator iterator = requestKeys.iterator();
                   while(iterator.hasNext()){
                        SelectionKey requestKey = (SelectionKey)iterator.next();
                        // Get the socket that's ready for IO.
                        ServerSocketChannel requestChannel = (ServerSocketChannel)requestKey.channel();
                        // This shouldn't block.
                        Socket requestSocket = requestChannel.accept();
                        inBuffer.clear();
                        requestSocket.read(inBuffer);                    
                        inBuffer.flip();
                        Charset charset = Charset.forName("ISO-8859-1");
                        CharsetDecoder decoder = charset.newDecoder();
                        charBuffer = decoder.decode(inBuffer);
                        iterator.remove();                    
    }

    Well its been about a month and a half so I guess you have your answer. In case you don't...
    // This shouldn't block.
    Socket requestSocket = requestChannel.accept();
    The problem is quite simple. The ServerSocketChannel.accept() returns a SocketChannel. (Channel -> Channel).
    You can get access to the socket using the SocketChannel.
    SocketChannel requestSocketChannel = requestChannel.accept();
    Socket requestSocket = requestSocketChannel.socket();
    But you don't need the socket to read and write.

  • Problem running a simple Hello World RMI Program

    I wrote a simple RMI application, consisting of a Server Interface, Server Implementation and a Client.
    Since the codes are really small, am pasting them here so that you could identify the problem if any, in the code.
    1. Server Interface......
    import java.rmi.* ;
    public interface HelloInterface extends java.rmi.Remote
         public void sayHello(String arg) throws RemoteException ;
    2. Server Implementation......
    import java.rmi.* ;
    import java.rmi.server.* ;
    public class HelloImpl extends UnicastRemoteObject implements HelloInterface
         public HelloImpl() throws RemoteException
              super() ;
         public void sayHello(String arg) throws RemoteException{
              try{
                   System.out.println("RMI Program : Hello "+arg) ;
              catch(Exception e){
                   e.printStackTrace() ;
                   //throw new java.rmi.UnexpectedException("undeclared checked exception", e);
         public static void main(String[] args) throws RemoteException
              try{
                   if( System.getSecurityManager() == null )
                        System.setSecurityManager( new RMISecurityManager() ) ;
                   HelloImpl impl = new HelloImpl() ;
                   Naming.bind("HelloService",impl) ;
                   System.out.println( "Service bound..." ) ;
              catch(Exception e){
                   e.printStackTrace() ;
                   //throw new java.rmi.UnexpectedException("undeclared checked exception", e);
    3. Client Code.
    import java.rmi.* ;
    import java.rmi.Naming.* ;
    class RMIClient
         public static void main(String[] args)
              try{
                   if(System.getSecurityManager()==null)
                        System.setSecurityManager( new RMISecurityManager() ) ;
                   HelloInterface helloInt = (HelloInterface) Naming.lookup("rmi://sand.cise.ufl.edu/HelloService") ;
                   helloInt.sayHello("Ranjit") ;
              catch(Exception e){
                   e.printStackTrace() ;
    I have double checked the classpaths and they all look fine..
    I have even unset the classpath from the shell which runs the rmiregistry..am still getting these errors..
    1. If i use the default java to run the application..this is the error that it spits..
    sand:24% java -Djava.security.policy=java.policy HelloImpl
    java.rmi.UnexpectedException: undeclared checked exception; nested exception is:
    java.lang.ClassNotFoundException: HelloImpl_Stub
    at sun.rmi.registry.RegistryImpl_Stub.bind(Unknown Source)
    at java.rmi.Naming.bind(Naming.java:110)
    at HelloImpl.main(HelloImpl.java:28)
    Caused by: java.lang.ClassNotFoundException: HelloImpl_Stub
    at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:247)
    at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:223)
    at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:350)
    ... 3 more
    2. Using java from some other location..the error looks different...but in both cases it just gives errors :((
    sand:25% /usr/java1.2/bin/java -Djava.security.policy=java.policy HelloImpl
    java.rmi.UnexpectedException: undeclared checked exception; nested exception is:
    java.lang.ClassNotFoundException: HelloImpl_Stub
    java.lang.ClassNotFoundException: HelloImpl_Stub
    at java.lang.Throwable.fillInStackTrace(Native Method)
    at java.lang.Throwable.fillInStackTrace(Compiled Code)
    at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Compiled Code)
    at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:223)
    at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:342)
    at sun.rmi.registry.RegistryImpl_Stub.bind(Unknown Source)
    at java.rmi.Naming.bind(Naming.java:116)
    at HelloImpl.main(HelloImpl.java:28)
    I am embarking on a huge assignment but if am having problems getting started..
    Your help will be highly appreciated..
    thanx and regards
    Ranjit Iyer

    First of all you should be posting this Q in the RMI forum :)
    You are getting that error because your stub is not in your clients classpath (or u can say the compiler is not able to find it).
    Make sure that the file HelloImpl_Stub is in the client classpath/package.
    Regards
    Meka Toka

  • How to make a simple hello world c program in xcode???

    Hello..... I've learnt the basics of c programming recently, They use code blocks (ver 10.05) in my class. Im new to Xcode.. so please can you help me?

    Go to http://www.netbeans.org/
    You should find tutorials there.

  • Exception in Hello World Program in Hibernate

    Hi All
    I am trying to run my first "Hello World" hibernate program in the book "Java Persitance with Hibernate". I have written the model class and the main class.
    I have also create the mapping file Message.hbm.xml and hibernate configuration file hibernate.cfg.xml through hibernate tools. Now when I am running the main class i am getting the following exception.
    SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
    SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
    Exception in thread "main" java.lang.ExceptionInInitializerError
         at com.hibernate.test.HibernateUtil.<clinit>(HibernateUtil.java:17)
         at com.hibernate.test.HelloWorld.main(HelloWorld.java:15)
    Caused by: java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder
         at org.slf4j.LoggerFactory.getSingleton(LoggerFactory.java:223)
         at org.slf4j.LoggerFactory.bind(LoggerFactory.java:120)
         at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:111)
         at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:269)
         at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:242)
         at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:255)
         at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:165)
         at com.hibernate.test.HibernateUtil.<clinit>(HibernateUtil.java:15)
         ... 1 more
    Caused by: java.lang.ClassNotFoundException: org.slf4j.impl.StaticLoggerBinder
         at java.net.URLClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClassInternal(Unknown Source)
         ... 9 moreI have added the following jars from the folder hibernate-distribution-3.5.2-Final\lib\required
    commons-collections-3.1.jar
    dom4j-1.6.1.jar
    javassist-3.9.0.GA.jar
    jta-1.1.jar
    slf4j-api-1.5.8.jar
    and hibernate3.jar to the classpath.
    It would be great if someone could help me in resolving this problem
    Thanks in advance
    Fierof2

    user13519911 wrote:
    I have posted this question here because this is a hibernate program with is related to database connectivity. What i would like to know is what is the jar file i am missing and why is it not present in the required folders of hibernate distribution.Yeah. With that kind of unproductive attitude I suddenly lose all interest in helping. So weird.
    Guess I'll do what I like: be blunt. You are allowed to think. I suggest you do so.

  • Running hello world

    Hello,
    I've installed java card, and i'd like to know how do i run Hello World?
    I have the .cap file but how do i get it to print the "Hello World" string in my console?
    Thanks,
    tikalius

    Did you read the Java Card Kit docu?

  • Cannot get a HELLO WORLD

    Please take the time to answer this very simple but ANNOYING question.
    does anybody know a good (preferably free) C compiler to build java compatable dll files??
    The ones that are supposedly "the best out there, ect" seem to alway want to link dll's to exe's which defeats the whole point of a dll
    Thanks in advance. Bamkin

    Installation
    Install the IDE; Sun's JDK with NetBeans for Java and Cygwin Unix shell for WinXXxx with GNU's gcc for C/C++ and Fortran
    Install Netbeans with JDK as a co-bundle
    Read More about J2SE http://java.sun.com/j2se/overview.html
    Read More about NetBeansTM http://www.netbeans.org/
    Download the Download NetBeans IDE v 3.5.1 with J2SE v 1.4.2 COBUNDLE
    http://java.sun.com/j2se/1.4.2/download.html
    For:
    Windows (.exe)
    Now install both at one step JDK and NetBeans
    Install the Netbeans-Module "cpp"
    This module adds the functionality of an C/C++ and Fortran editor with syntax-highlighting for view and print:
    1) Open your NetBeans
    Go with your browser to: http://www.netbeans.org/catalogue/32-stable.html
    and select the download button for CPP support: http://www.netbeans.org/download/nbms/33/stable/Unmaintained/cpplite.nbm
    If your NetBeans installation is valid you can open it direct with your browser for the NetBeans installation process.
    Configure the syntax highlighting in Java and in ?cpp? as you like in font, color and font-settings.
    For print:
    at: Menue>Tools>Options/IDE Configuration/System/Print Settings/C and C++Editor>Font & Colors(click)>Button?...?(click)>Frame:?Print Fonts and Colors?
    At this Frame you have a list of the recognized syntax-elements and on the right side you can change there styles in font, font-settings, colors and see a preview of the actual settings.
    For java, XML and all other do the same in the ?Print Settings? as you like most.
    For screen-view:
    at: Menue>Tools>Options/Editing/Editor Settings/C and C++Editor>Font & Colors(click)>Button?...?(click)>Frame:?Fonts and Colors?
    The frame works as that for print does.
    Install Cygwin, the UNIX-Shell running in windows!
    I will explain the way starting from web:
    Go to:
    http://www.cygwin.com/setup.exe
    and start the setup.exe
    You have to choose:
    1) Install from Internet
    2) your directory for cygwin like: "D:\Programme\cygwin" and the install for all or just for you
    3) choose a local package directory like "D:\Programme\cygwin"
    4) choose the settings to access the web like "Use IE5 Settings"
    5) choose the nearest you download server
    6) Selection of the required packages
    The Developer Package:
    A tree of packages is listed you have to click at 6. line (+Devel) at the word Default
    +Devel # Default
    Default should changed to:
    +Devel # Install
    ...this is your developer-pack including gcc
    The Win32-API libraries:
    but further you have to go to Libs (line 12) and now click to the '+' -sign:
    + Libs # Default
    The lib tree should now opened.
    go up to the 5. last line at the 6. column "Package" you should read w32api: Win32 API header and library ...
    look back to column 3 "New" there stands Skip click on it [as long] that you see the version number (2.5-1) or any better
    The Documentation:
    The Documentation should help but it is not necessary to install it:
    + Doc # Default (line 7)
    so that it changes to
    + Doc # Install.
    Now you can finish your installation!
    Follow the steps to finish the installation.
    Overview to JINI by a simple example
    Java code using an external native dll function from java
    This is the view of the resulting directory-file-structure
    For all the steps sampleRoot stands for your root to work with this sample!
    +- sampleRoot
       +- com
       |  +- myPackage
       |     +HelloWorldCaller.java
       |     +HelloWorldCaller.class
       +HelloWoldImp.c
       +HelloWoldImp.dll
       +com_myPackage_HelloWorldCaller.h
    The Java-code:
    This code have a package-declaration so it resists at the subdirectories sampleRoot/com/myPackage!
    package com.myPackage;
    * HelloWorldCaller.java
    * Created on 26. M?rz 2004, 13:23
    * @author  mike
    class HelloWorldCaller {
        //the declaration for the native method
        public native void displayHelloWorld();
        //this part of code is executed while class is loaded
        static {
            //loads the native library from native systems path
            System.out.println("start to load the library");
            System.loadLibrary("HelloWorldImp");
            System.out.println("load should already be done");
        //the constructor is empty and can be cleared
        public HelloWorldCaller(){
        //this is a caller for the native method but you can do it direct at main
        public void doNativeCall(){
            displayHelloWorld();
        public static void main(String[] args) {
            //instantiate and call from this instance the native method
            new HelloWorldCaller().doNativeCall();
            //this is the same without a calling method between
            new HelloWorldCaller().displayHelloWorld();
    Compile the Code:
    You working-directory is the sampleRoot!
    $ javac com/myPackage/HelloWorldCaller.java
    Generate the C-Header File
    You working-directory is the sampleRoot!
    $ javah com.myPackage.HelloWorldCaller
    The naming convention of the resulting header-file:
    automatic generated by javah
    Syntax of the C-header file name:
    <packagename truncated with '_'>_<classname>.h
    If you use no package this part ?<packagename truncated with '_'>_? is simply left.
    +-- package name truncated with underscore
                  +-- class name
                                  + ending of a header filecom_myPackage_HelloWorldCaller.h
    The naming convention of the resulting method declaration:
    Syntax of the function signature:
    Java_<packagename truncated with '_'>_<classname>_<functionname>
    If you use no package this part ?<packagename truncated with '_'>_? is simply left.
    +-- Java
        + Underscore
         +-- package name truncated with underscore
                       +-- class name
                                       +-- underscore
                                        +-- method nameJava_com_myPackage_HelloWorldCaller_displayHelloWorld
    The generated - com_myPackage_HelloWorldCaller.h -file:
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class com_myPackage_HelloWorldCaller */
    #ifndef _Included_com_myPackage_HelloWorldCaller
    #define _Included_com_myPackage_HelloWorldCaller
    #ifdef __cplusplus
    extern "C" {
    #endif
    * Class:     com_myPackage_HelloWorldCaller
    * Method:    displayHelloWorld
    * Signature: ()V
    JNIEXPORT void JNICALL Java_com_myPackage_HelloWorldCaller_displayHelloWorld
      (JNIEnv *, jobject);
    #ifdef __cplusplus
    #endif
    #endif
    The implementation of the native dll function - HelloWorldImp.c -file
    * File:   HelloWorldImp.c
    * Author: mike
    * Created on 26. M?rz 2004, 14:34
    #include <jni.h>
    #include <stdio.h>
    #include "com_myPackage_HelloWorldCaller.h"
    /* The implementation of the native method
    JNIEXPORT void JNICALL Java_com_myPackage_HelloWorldCaller_displayHelloWorld(JNIEnv *env, jobject obj)
        printf("Hello world!\n");
        return;
    Compile the HelloWorldImp.c ? file to a *.dll
    On MS Win with Cygwin, the following command builds a dynamic link library HelloWorldImp.dll:
    This command is one line without line-breaks.
    Check your include because I use the j2sdk1.4.2_04 if you want to do like me than install it.
    For j2sdk1.4.2_04:
    $ gcc -Wall -mno-cygwin  -I/cygdrive/c/j2sdk1.4.2_04/include
    -I/cygdrive/c/j2sdk1.4.2_04/include/win32 -shared
    HelloWorldImp.c -Wl,--add-stdcall-alias -o HelloWorldImp.dllFor j2sdk1.4.2 as co-installation with NetBeans:
    $ gcc -Wall -mno-cygwin  -I/cygdrive/c/j2sdk1.4.2/j2sdk1.4.2/include
    -I/cygdrive/c/j2sdk1.4.2/j2sdk1.4.2/include/win32 -shared
    HelloWorldImp.c -Wl,--add-stdcall-alias -o HelloWorldImp.dll
    The used Switches:
    -Wall : switches on all warnings
    -mno-cygwin : switches off the use of unix-API's, instead of it uses win32-calls
    -I<directory> : defines a path to a directory with include *.h-files
    -shared : advices the compiler to make shared libraries (*.so for linux and *.dll for win)
    -Wl,<option> : Pass an option to the linker (for Wl: l is an L not an 1 and stands for linker)
    -Wl,--add-stdcall-alias : pass the switch --add-stdcall-alias to the linker, advices the linker to add standardcalls so the exports have an standard-call alias as well.
    The exports of the resulting dll:
    If you want to test the exports yourself use : http://ftp.berlios.de/pub/unimatrix-fulda/win-devel/impdef.zip and compile it.
    impdef.exe is a small program resulting the dll's EXPORTS to standard-device, screen:
    $ impdef HelloWorldImp.dll
    EXPORTS
    Java_com_myPackage_HelloWorldCaller_displayHelloWorld
    Java_com_myPackage_HelloWorldCaller_displayHelloWorld@8On Linux:
    Not tested, only a sample copy from an other helping guy's text!
    gcc -I../ -o libtestjni.so testjni.c ***many .a and .o here*** -shared -Wl,-soname,libnative.so
    -I/usr/java/jdk/include -I/usr/java/jdk/include/linux -static -lc
    On Solaris, the following command builds a shared library libhello.so:
    Not tested, only a sample copy from an other helping guy's text!
    cc -G -I/usr/local/java/include -I/usr/local/java/include/solaris \
    HelloWorldImp.c -o libhello.so
    On Microsoft Windows, the following command builds a dynamic link library hello.dll using Microsoft Visual C++ 4.0:
    Not tested, only a sample copy from an other helping guy's text!
    cl -Ic:\java\include -Ic:\java\include\win32
    -LD HelloWorldImp.c -Fehello.dll
    Set Your Library Path
    DOS shell (Windows 95/NT)
    On Windows 9x/NT/2000/(XP), the loadLibrary() method searches for DLLs in the same manner as other language environments do.
    The java.library.path is the same as the systems %PATH%-variable.
    Add the directory where your *.dll-file exists
    SET PATH=%PATH%;X:YourDirectory
    or copy your *.dll-file to one of the allready in the PATH mounted directories.
    UNIX
    % setenv LD_LIBRARY_PATH mylibrarypath
    where mylibrarypath is the name of the directory that contains libhello.so.
    MacOS
    The Java runtime searches the JavaSoft Folder in the Extensions folder in the System Folder for shared libraries. Create an alias to your shared library in the JavaSoft Folder.
    Execute the code
    If it works fine:
    $ java com.myPackage.HelloWorldCaller
    start to load the library
    load should already be done
    Hello world!
    If the dll is not found you get:
    $ java com.myPackage.HelloWorldCaller
    start to load the library
    Exception in thread "main" java.lang.UnsatisfiedLinkError: no HelloWorldImp in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1491)
    at java.lang.Runtime.loadLibrary0(Runtime.java:788)
    at java.lang.System.loadLibrary(System.java:834)
    at com.myPackage.HelloWorldCaller.<init>(HelloWorldCaller.java:24)
    at com.myPackage.HelloWorldCaller.main(HelloWorldCaller.java:34)
    The java.library.path is not as he should be see: ?Set Your Library Path?
    If the dll is loaded, but the native method is not reachable you get something like:
    $ java com.myPackage.HelloWorldCaller
    Exception in thread "main" java.lang.UnsatisfiedLinkError: displayHelloWorld
    at com.myPackage.HelloWorldCaller.displayHelloWorld(Native Method)
    at com.myPackage.HelloWorldCaller.main(HelloWorldCaller.java:25)
    Check the Naming of your native methods C-implementation and the generation of standard-calls.

  • Problem with JNI hello world

    I found some tutorial on SUN site on how to use JNI. I'm using Eclipse to compije Java and C (via Cygwin) files. Here are complete files:
    Hello.java:
    class Hello
         public native void sayHello();
         static
              try
              System.loadLibrary("hello");
              catch(Exception e)
                   System.out.println("exc");
         public static void main(String[] args)
              Hello h = new Hello();
              h.sayHello ();
    }Hello.c:
    #include <mingw/_mingw.h> //because there are some types needed for JNI
    #include <jni.h>
    #include "Hello.h"
    #include <stdio.h>
    JNIEXPORT void JNICALL Java_Hello_sayHello
      (JNIEnv *env, jobject obj)
         printf("Hello world!\n");
         return;
    }Makefile:
    hello.dll : Hello.o Hello.def
         gcc -g -shared -Wl,--kill-at -o hello.dll Hello.o hello.def
    Hello.o : Hello.c Hello.h
         gcc -c -g -I"$(JAVA_HOME)\include" -I"$(JAVA_HOME)\include\win32" Hello.c -o Hello.o
    Hello.h : Hello.class
         javah -jni Hello
    clean :
         rm Hello.h
         rm Hello.o
         rm hello.dllHello.def
    EXPORTS
    Java_Hello_sayHelloEverything goes well, but when I run java program it does nothin (it should print message, but it just exit without any error).I'm sure that it's something stupid, but I cant see what. Can anyone tell me what am I doing wrong?
    Thenks.

    Answer 1: yes, there was no problem. I compiled and started simple 'hello world' program from Cygwin and from WinXP console, and it worked well.
    Answer 2: This is weird, I changed code to this:
    Hello.java:
         public native int getInt();
              System.out.println("Returned int is " + h.getInt());Hello.c:
    JNIEXPORT jint JNICALL Java_Hello_getInt
      (JNIEnv *env, jobject obj)
         return 25;
    }It does not print anything. I started this program from Cygwin and from WinXP console, and from Eclipse. Only if I debug in Eclipse (step by step) I get:
    Returned int is 25and still I don't get Hello string printed (even if I go step by step). It looks like cygwin has some problem with OS. Do you have any idea what to do, I'm a bit confused?
    Thank you.
    Message was edited by:
    zly

Maybe you are looking for