Need help w. Java Networking.

  • Thread starter Steve R. Burrus
  • Start date
S

Steve R. Burrus

I am trying to run this simple example of some Java Networking. The
example is called "httpServer.java", and I believe that it uses a HTTP
Server, very much like the Apache Server! I can compile it okay, but
when I go to running it, using the command "java httpServer [num. of the
HTTP Server port], I am afraid that I always get back this error ! :

"java.lang.NoClassDefFoundError: C:\MyJavaFiles\httpServer/java
Exception in thread "main" " Here is the entire code for the program.
What could be wrong with it?

"// a simple example of some Java Networking.

import java.net.*;
import java.io.*;
import java.util.*;
import java.lang.*;


public class httpServer
{

public static void main(String args[]) {

int port;
ServerSocket server_socket;


try {
port = Integer.parseInt(args[0]);
}
catch (Exception e) {
port = 1500;
}


try {

server_socket = new ServerSocket(port);
System.out.println("httpServer running on port " +
server_socket.getLocalPort());

// server infinite loop
while(true) {
Socket socket = server_socket.accept();
System.out.println("New connection accepted " +
socket.getInetAddress() +
":" + socket.getPort());

// Construct handler to process the HTTP request message.
try {
httpRequestHandler request =
new httpRequestHandler(socket);
// Create a new thread to process the request.
Thread thread = new Thread(request);

// Start the thread.
thread.start();
}
catch(Exception e) {
System.out.println(e);
}
}
}

catch (IOException e) {
System.out.println(e);
}
}
}



class httpRequestHandler implements Runnable
{
final static String CRLF = "\r\n";
Socket socket;
InputStream input;
OutputStream output;
BufferedReader br;

// Constructor
public httpRequestHandler(Socket socket) throws Exception
{
this.socket = socket;
this.input = socket.getInputStream();
this.output = socket.getOutputStream();
this.br =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
}

// Implement the run() method of the Runnable interface.
public void run()
{
try {
processRequest();
}
catch(Exception e) {
System.out.println(e);
}
}

private void processRequest() throws Exception
{
while(true) {

String headerLine = br.readLine();
System.out.println(headerLine);
if(headerLine.equals(CRLF) || headerLine.equals("")) break;

StringTokenizer s = new StringTokenizer(headerLine);
String temp = s.nextToken();

if(temp.equals("GET")) {

String fileName = s.nextToken();
fileName = "." + fileName ;

// Open the requested file.
FileInputStream fis = null ;
boolean fileExists = true ;
try
{
fis = new FileInputStream( fileName ) ;
}
catch ( FileNotFoundException e )
{
fileExists = false ;
}

// Construct the response message.
String serverLine = "Server: fpont simple java httpServer";
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
String contentLengthLine = "error";
if ( fileExists )
{
statusLine = "HTTP/1.0 200 OK" + CRLF ;
contentTypeLine = "Content-type: " +
contentType( fileName ) + CRLF ;
contentLengthLine = "Content-Length: "
+ (new Integer(fis.available())).toString()
+ CRLF;
}
else
{
statusLine = "HTTP/1.0 404 Not Found" + CRLF ;
contentTypeLine = "text/html" ;
entityBody = "<HTML>" +
"<HEAD><TITLE>404 Not Found</TITLE></HEAD>" +
"<BODY>404 Not Found"
+"<br>usage:http://yourHostName:port/"
+"fileName.html</BODY></HTML>" ;
}

// Send the status line.
output.write(statusLine.getBytes());

// Send the server line.
output.write(serverLine.getBytes());

// Send the content type line.
output.write(contentTypeLine.getBytes());

// Send the Content-Length
output.write(contentLengthLine.getBytes());

// Send a blank line to indicate the end of the header lines.
output.write(CRLF.getBytes());

// Send the entity body.
if (fileExists)
{
sendBytes(fis, output) ;
fis.close();
}
else
{
output.write(entityBody.getBytes());
}

}
}

try {
output.close();
br.close();
socket.close();
}
catch(Exception e) {}
}

private static void sendBytes(FileInputStream fis, OutputStream os)
throws Exception
{
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024] ;
int bytes = 0 ;

// Copy requested file into the socket's output stream.
while ((bytes = fis.read(buffer)) != -1 )
{
os.write(buffer, 0, bytes);
}
}

private static String contentType(String fileName)
{
if (fileName.endsWith(".htm") || fileName.endsWith(".html"))
{
return "text/html";
}

return "";

}

} "
 
M

mromarkhan

Peace.
"java.lang.NoClassDefFoundError: C:\MyJavaFiles\httpServer/java
Exception in thread "main" " Here is the entire code for the program.
[snip][snip]

I guess you are appending .java to the end.

Reproducable test case:
C:\My Documents\Omar\nntp-test\Java_1_1>java Client.java
Exception in thread "main" java.lang.NoClassDefFoundError: Client/java

just a guess.

Have a good day.
 
S

Steve R. Burrus

I guess you are appending .java to the end.

No, I can assure you that I have been working with the Java Programming
language long enough to NOT dare do that, what you imply!!! Someone
recently in this group said to put a -cp switch with the java
interpreter command, and it DID allow/permit me to see a particular Java
program. Should I do it here with this Java networking program??
 
M

mromarkhan

Peace be unto you
Should I do it here with this Java networking program??

Sure, why not?

By the way, it works super for me.
Since your eXPerienced with Java programming,
I can not think of a reason why
it might not work for you.

But for the NOVICE who might stumble
upon this thread,

another reason
might be that is it non existant and the error is true

test case:
java c:\MuFiles\me
java.lang.NoClassDefFoundError: c:\MuFiles\me
Exception in thread "main" >Exit code: 1
I do not have me.class in c:\MuFiles, let alone the directory


another reason
might be that it is part of a package.

test case:
package org.apachereplacement;
import java.net.*;
import java.io.*;
import java.util.*;
.........snip code
javac httpServer.java
Exit code: 0 java httpServer
java httpServer
java.lang.NoClassDefFoundError: httpServer (wrong name: org/apachereplacement/httpServer)
.....
Exception in thread "main" >Exit code: 1
But of course, this produces a *different*
error message


Have a good day.


Appendix A - Output of nice http server class
javac httpServer.java
Exit code: 0
java httpServer
httpServer running on port 1500
New connection accepted /127.0.0.1:1330
GET / HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, application/x-gsarcade-launch, */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Win 9x 4.90; T312461; .NET CLR 1.1.4322)
Host: localhost:1500
Connection: Keep-Alive

New connection accepted /127.0.0.1:1331
GET /httpServer.java HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, application/x-gsarcade-launch, */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Win 9x 4.90; T312461; .NET CLR 1.1.4322)
Host: localhost:1500
Connection: Keep-Alive


java httpServer 1500
java httpServer 1500
httpServer running on port 1500


java httpServer 1200
java httpServer 1200
httpServer running on port 1200
 
S

Steve R. Burrus

another reason
might be that it is part of a package.

test case:
package org.apachereplacement;
import java.net.*;
import java.io.*;
import java.util.*;
........snip code

java httpServer


java.lang.NoClassDefFoundError: httpServer (wrong name: org/apachereplacement/httpServer)
....
Exception in thread "main" >Exit code: 1
But of course, this produces a *different*
error message

Hey friend, thanx a lot for the most detailed bit of help/assistance
that I have received yet about this Java Networking problem of mine!!
Listen, you referred in your post to a possible package that my Java
file could be in. As a matter of fact, it IS in a package, something
like "com.stephen.burrus"!! So, after it's successfully compiled in DOS,
to run the program, I should probably refer to the entire package name
that the class file is in, like "java com\stephen\burrus\httpServer"???
 
R

Ryan Stewart

Steve R. Burrus said:
Hey friend, thanx a lot for the most detailed bit of help/assistance
that I have received yet about this Java Networking problem of mine!!
Listen, you referred in your post to a possible package that my Java
file could be in. As a matter of fact, it IS in a package, something
like "com.stephen.burrus"!! So, after it's successfully compiled in DOS,
to run the program, I should probably refer to the entire package name
that the class file is in, like "java com\stephen\burrus\httpServer"???
If it's in a package, you *must* run it like that. And class names should
start with a capital letter, like HttpServer.
 
S

Steve R. Burrus

Ryan said:
If it's in a package, you *must* run it like that. And class names should
start with a capital letter, like HttpServer.

Well, I re-named the "httpServer.java" file to the "HttpServer.java"
file in DOS earlier, then tried my luck with running the Java intepreter
on it, but alas, this is what I STILL got back in the way of an error!!!

"C:\HMI\servletbible\ch04\examples>java
servletbible\ch04\examples\HttpServer 80
Exception in thread "main" java.lang.NoClassDefFoundError:
servletbible\ch04\examples\HttpServer"

And I also tried attaching the .class file extension to it, but that
didn't help any, so where am I going wrong now??
 
R

Ryan Stewart

Steve R. Burrus said:
Well, I re-named the "httpServer.java" file to the "HttpServer.java"
file in DOS earlier, then tried my luck with running the Java intepreter
on it, but alas, this is what I STILL got back in the way of an error!!!

"C:\HMI\servletbible\ch04\examples>java
servletbible\ch04\examples\HttpServer 80
Exception in thread "main" java.lang.NoClassDefFoundError:
servletbible\ch04\examples\HttpServer"

And I also tried attaching the .class file extension to it, but that
didn't help any, so where am I going wrong now??
Question: Why are you bothering with trying to compile an HTTP server if you
don't even know the very basics of Java? I'd suggest you spend some time
here:
http://java.sun.com/docs/books/tutorial/

To answer your question, it looks like you should be running it from the
C:\HMI directory, assuming you've correctly identified the package as
servletbible.ch04.examples.

Finally, this kind of basic question belongs in comp.lang.java.help.
 
S

Sudsy

Steve said:
Ryan Stewart wrote:
"C:\HMI\servletbible\ch04\examples>java
servletbible\ch04\examples\HttpServer 80
javac -d . HttpServer.java
java -classpath %CLASSPATH%;. org.apachereplacement.HttpServer

This advice has been provided to you on many occasions already.
The '-d .' (note the space before the dot) tells the compiler
to use the current directory as the destination directory. You
posted code earlier which specified a package of org.apachereplacement
so the class file will end up here:
.\org\apachereplacement\HttpServer.class
When you want to run the class, you have to specify the current
directory in the classpath (hence the addition of the . following
a semi-colon in the command line) and the name of the class. Note
that you replace the file separator (the backslash on M$) with the
.. (period).
Clear?
 
C

Chris Smith

Steve said:
"C:\HMI\servletbible\ch04\examples>java
servletbible\ch04\examples\HttpServer 80
Exception in thread "main" java.lang.NoClassDefFoundError:
servletbible\ch04\examples\HttpServer"

That should be:

C:\HMI> java servletbible.ch04.examples.HttpServer 80

Two things:

1. The classpath (which is by default the current working directory)
should be the top-level location that contains your classes. The
compiler then knows to look in servletbible\ch04\examples because of the
class's fully qualified name.

2. Fully qualified class names are written with '.' as the separator for
package elements. You appear to be confusing class names with file
names, and thus trying to use '\' as a separator, but that's not going
to work.
And I also tried attaching the .class file extension to it, but that
didn't help any, so where am I going wrong now??

And that confirms that you're confusing class names with file names. To
put this clearly: the argument to javac is the fully qualified class
name, *not* the path to the file that contains the class. The compiler
will then go find the class file on its own, based on the fully
qualified class name and the classpath.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
B

Bryce

Well, I re-named the "httpServer.java" file to the "HttpServer.java"
file in DOS earlier, then tried my luck with running the Java intepreter
on it, but alas, this is what I STILL got back in the way of an error!!!

I presume that not only did you rename your file to HttpServer.java,
you also changed the class def to read
public class HttpServer {

make sure:

1. You are at the root directory of your project. from that directory,
there should be a subdirectory servletbible\ch04\examples. In that
subdirectory should be a file HttpServer.class
"C:\HMI\servletbible\ch04\examples>java
servletbible\ch04\examples\HttpServer 80
Exception in thread "main" java.lang.NoClassDefFoundError:
servletbible\ch04\examples\HttpServer"

And I also tried attaching the .class file extension to it, but that
didn't help any, so where am I going wrong now??

2. No. You do not need to use the .class file extension.

3. This should work then

java -servletbible.ch04.examples.Httpserver
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top