0

Goal:

My goal with this code is to create a simple web server that can handle multiple clients, and that will respond with the html to say "hi" when the client requests it.

Code:

Here's test number one. It only can handle one client once:

import java.net.*;
import java.io.*;
 public class Webserver1 { 
     public static void main(String[] args) { 
         ServerSocket ss;
         Socket s;
         try {
             //set up connection
             ss = new ServerSocket(80);
             s = ss.accept();
         } catch (Exception e) {
             System.out.println(e.getMessage());
             return;
         }
         try (
                 BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                 DataOutputStream out = new DataOutputStream (s.getOutputStream());
                 ) {
             String inline = in.readLine();
             //http request
             if (inline.startsWith("GET")) {
             //return http
                 out.writeBytes("<!doctype html><html><body><p>hi</p></body></html>");
             }
         } catch (Exception e) {
             System.out.println(e.getMessage());
         }
     }
 } 

Here's test number two. It is meant to handle multiple clients:

import java.net.*;
import java.io.*;
public class Webserver2 {  
//class to handle connections
     public static class server {
        ServerSocket ss;
        Socket s[] = new Socket[maxn];
        public server () {
            try {
            ss = new ServerSocket(80);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
    }
        public InputStream getis(int num) throws Exception {
            return s[num].getInputStream();
        }
        public OutputStream getos(int num) throws Exception {
            return s[num].getOutputStream();
        }
        public void close() throws Exception {
            for (int i = 0; i < numc; i++) {
            s[i].close();
            }
        }
        public void newc () throws Exception {
            s[numc + 1] = ss.accept();
        }
    }
     static int numc = 0;
     static final int maxn = 100;
     static server se = new server();
     public static void main(String[] args) {
         try {
        while (numc < 6) {
        //set up connection, and start new thread
         se.newc();
         numc++;
         System.out.println("0");
         (new Client()).start();
         }
         } catch (Exception e) {
             System.out.println(e.getMessage());
         }
     }
     public static class Client extends Thread {
         public void run() {
             try(
                     BufferedReader in = new BufferedReader(new InputStreamReader(se.getis(numc)));
                     DataOutputStream out = new DataOutputStream (se.getos(numc));
                     ) {
                 String inline;
                 while(true) {
                         inline = in.readLine();
                         //wait for http request
                     if (inline.startsWith("GET")) {
                         System.out.println("1");
                         //respond with header, and html
                         out.writeBytes("HTTP/1.1 200 OK\r\n");
                         out.writeBytes("Connection: close\r\n");
                         out.writeBytes("Content-Type: text/html\r\n\r\n");
                         out.writeBytes("<!doctype html><html><body><p>hi</p></body></html>");
                         out.flush();
                     }
                 }
             } catch (Exception e) {
                 System.out.println(e.getMessage());
             }
         }
     }
}

Problems:

On my computer, if I run the first example, and on my browser I type: "http://192.168.1.xxx", I get a simple "hi". However, on the second one if I try the same thing it simply doesn't work. But if in the command prompt I type: telnet 192.168.1.xxx 80, then type GET it sends back the html. Also, if I replace the DataOutputStream with a PrintWriter, it doesn't even send it to the telnet. However, I know it tries because the program prints "0" every time a connection is made, and "1" every time it prints something.

Questions:

  • What is the problem that prevents the browser from viewing the html?

  • Does it have to do with the html itself, the way I set up my connection, or the DataOutputStream?

  • How can I fix this?

Evan
  • 11
  • 2

1 Answers1

0

Don't use port 80, use some other random port greater than 6000. And if you didn't close your first program properly, port 80 is still used by that program.

I used a Http server program that is similar to this. The server also creates multiple threads for each connections, so the number of clients in not limited to 100.

` public class MultiThreadServer implements Runnable { Socket csocket; static int portno; static String result; MultiThreadServer(Socket csocket) { this.csocket = csocket; }

 public static void main(String args[]) 
 throws Exception 
 {
  portno=Integer.parseInt(args[0]); 
  ServerSocket srvsock = new ServerSocket(portno);
  System.out.println("Listening");
  while (true) {
     Socket sock = srvsock.accept();
     System.out.println("Connected");
     new Thread(new MultiThreadServer(sock)).start();
   }
  }
  public void run()
  { 
   String[] inputs=new String[3];
    FileInputStream fis=null;
    String file=null,status=null,temp=null;
    try
    {
            InputStreamReader ir=new     InputStreamReader(csocket.getInputStream());
        BufferedReader br= new BufferedReader(ir);
        DataOutputStream out = new   DataOutputStream(csocket.getOutputStream());
        String message=br.readLine();
        inputs=message.split(" ");
        if(inputs[0].equals("GET"))
            {
            try{
                 out.writeBytes("HTTP/1.1 200 OK\r\n");
                 out.writeBytes("Connection: close\r\n");
                 out.writeBytes("Content-Type: text/html\r\n\r\n");
                 out.writeBytes("<!doctype html><html><body><p>hi</p></body>  </html>");
                }
                out.flush();                      
            fis.close();    
            csocket.close();
            }
            catch(Exception ex)
            {
                status="404 File not found";
                os.println(status);

            }
   }`
  • Greater than 6000... this is very random, also if he was able to work on 80 from his computer, the port was not an issue. – Alexandre Lavoie Mar 25 '15 at 05:55
  • Thanks for the answer! New and improved code works great. Turns out the problem was I needed to close the socket after sending the html, the browser thought I was still sending information – Evan Mar 26 '15 at 16:45