Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

MultiThreaded web server

Status
Not open for further replies.

sn128

Programmer
Dec 3, 2002
13
GB
Hi, I am very new to java and trying to make this server multithreaded to handle repeated concurrent requests. I would a new thread to handle each connection.

Help would be great

Many Thanks



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

class Web extends Thread
{
public static void main(String[] args) throws Exception
{
String requestMessageLine;
String fileName;
ServerSocket listenSocket = new ServerSocket(8005);
while(true){
Socket connectionSocket = listenSocket.accept();

BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(
connectionSocket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(
connectionSocket.getOutputStream());

requestMessageLine = inFromClient.readLine();
StringTokenizer tokenizedLine =
new StringTokenizer(requestMessageLine);

if (tokenizedLine.nextToken().equals("GET"))
{
fileName = tokenizedLine.nextToken();

if ( fileName.startsWith("/")==true )
fileName = fileName.substring(1);
File file = new File(fileName);
int numOfBytes = (int)file.length();
FileInputStream inFile = new FileInputStream(fileName);

byte[] fileInBytes = new byte[numOfBytes];
inFile.read(fileInBytes);

/* Send the HTTP header */
outToClient.writeBytes("HTTP/1.1 200 Document Follows\r\n");

if (fileName.endsWith(".jpg"))
outToClient.writeBytes("Content-Type: image/jpeg\r\n");

if (fileName.endsWith(".gif"))
outToClient.writeBytes("Content-Type: image/gif\r\n");

if (fileName.endsWith(".html"))
outToClient.writeBytes("Content-Type: html/jpeg\r\n");

outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
outToClient.writeBytes("\r\n");

/* Now send the actual data */
outToClient.write(fileInBytes, 0, numOfBytes);
connectionSocket.close();

}
else
System.out.println("Bad Request Message");
}

}
}
 
Search the java.sun.com site for "webserver" There you can find a multi-threaded java webserver written for you. I have used it, and there are a few bugs in the source code.

First there's a &quot;/&quot; for the comment at the top of the code. And when the server is listing a directory, there is a &quot;<&quot; missing in one of the html strings.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top