Results 1 to 5 of 5
Like Tree1Likes
  • 1 Post By tejalekya

Thread: Can I improve this code?

  1. #1
    jobud9 is offline Member
    Join Date
    Dec 2011
    Posts
    34
    Rep Power
    0

    Default Can I improve this code?

    This is a simple http socket server I've been working on.. I was wondering if it is ready to handle a few requests or if their is anything I should revise before I send it out:
    Java Code:
    package com.jobud9.Chatterbox;
    
    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class FileServer implements Runnable{
    	private ServerSocket serversocket = null;
    	public final Main plugin;
    	public FileServer(Main plugin) {
    		this.plugin = plugin;
    	}
    
    	public void run(){
    		int port = plugin.config.getInt("webserver.port");
    		try {
    			serversocket = new ServerSocket(port);
    			plugin.toConsole("Server port bound!", 1);
    		}
    		catch (Exception e){
    			plugin.toConsole("Cannot bind to port"+port+"! It is allready in use.",3);
    			plugin.toConsole("shutting down webserver! please free port "+port+" or change the selected port in the config!", 3);
    		}
    		while (true) {
    			try {
    				Socket connectionsocket = serversocket.accept();
    				http_handler(new BufferedReader(new InputStreamReader(connectionsocket.getInputStream())), new DataOutputStream(connectionsocket.getOutputStream()));
    			}
    			catch (Exception e) {
    				plugin.toConsole("Error:" + e.getMessage(),2);
    			}
    		}
    	}
    	public void stop(){
    		try {
    			serversocket.close();
    		} catch (IOException e) {
    			plugin.toConsole("Error! cannot close the webserver!", 2);
    			e.printStackTrace();
    		}
    	}
    
    	private void http_handler(BufferedReader input, DataOutputStream output){
    		String path = new String();
    		try {
    			String tmp = input.readLine();
    			String tmp2 = new String(tmp);
    			tmp.toUpperCase();
    			int start = 0;
    			int end = 0;
    			for (int a = 0; a < tmp2.length(); a++) {
    				if (tmp2.charAt(a) == ' ' && start != 0) {
    					end = a;
    					break;
    				}
    				if (tmp2.charAt(a) == ' ' && start == 0) {
    					start = a;
    				}
    			}
    			path = tmp2.substring(start + 2, end);
    		}
    		catch (Exception e) {
    			plugin.toConsole("Error: "+e.getMessage(),2);
    			e.printStackTrace();
    		}
    
    		FileInputStream requestedfile = null;
    
    		try {
    			if(path.matches("applet.class")|| path.matches("applet$EventHandler.class") || path.matches("dirt.png") || path.matches("stone.png") || path.matches("grass.png")
    			|| path.matches("banner.png")||path.matches("grass.png") || path.matches("banner.png") || path.matches("index.html") || path.matches("favicon.ico")){
    				requestedfile = new FileInputStream("plugins"+File.separator+"Chatterbox"+"html"+File.separator+path);
    			}
    			else{
    				requestedfile = new FileInputStream("plugins"+File.separator+"Chatterbox"+"html"+File.separator+"index.htm");
    			}
    
    		} catch (FileNotFoundException e) {
    			plugin.toConsole("could not find file \""+path+"\" please make sure it is there!", 2);
    		}
    
    		try {
    			int file_type;
    			if(path.matches("dirt.png")){
    				file_type = 1;
    			}
    			else if(path.matches("banner.png")){
    				file_type = 1;
    			}
    			else if(path.matches("grass.png")){
    				file_type = 1;
    			}
    			else if(path.matches("stone.png")){
    				file_type = 1;
    			}
    			else if(path.matches("favicon.ico")){
    				file_type = 3;
    			}
    			else if(path.matches("applet.class")){
    				file_type = 2;
    			}
    			else if(path.matches("applet$EventHandler.class")){
    				file_type = 2;
    			}
    			else{
    				file_type = 0;
    			}
    			output.writeBytes(construct_http_header(file_type));
    			while (true) {
    				int b = requestedfile.read();
    				if (b == -1) {
    					break;
    				}
    				output.write(b);
    			}
    
    			output.close();
    			requestedfile.close();
    		}
    		catch (Exception e) {}
    
    	}
    
    	private String construct_http_header(int file_type) {
    		String s = "HTTP/1.0 ";
    		s = s + "200 OK";
    		s = s + "\r\n";
    		s = s + "Connection: close\r\n";
    
    		switch (file_type) {
    		case 0:
    			s = s + "Content-Type: text/html\r\n";
    			break;
    		case 1:
    			s = s + "Content-Type: image/png\r\n";
    			break;
    		case 2:
    			s = s + "Content-Type: application/x-java-applet\r\n";
    			break;
    		case 3:
    			s = s + "Content-Type: image/vnd.microsoft.icon\r\n";
    			break;
    		default:
    			s = s + "Content-Type: text/html\r\n";
    			break;
    		}
    
    		s = s + "\r\n";
    		return s;
    	}
    
    }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default Re: Can I improve this code?

    1)Use final String variables to define String used in the code instead of having multiple copies of the same String being hard coded into the code at various places. This will prevent typo bugs.: "applet.class" vs "Applet.class"

    2)Add comments to describe what the logic around this statement is:
    if (tmp2.charAt(a) == ' ' && start != 0) {

  3. #3
    tejalekya is offline Member
    Join Date
    Feb 2012
    Posts
    2
    Rep Power
    0

    Default Re: Can I improve this code?

    If your socket should accept multiple incoming connections, then immediately after a connection is got you got to launch a thread so that your socket is again waitng for incoming connectins. In your case unless http_handler() function is complete, the server will not be in a position to accept another incoming connection. I hope iam clear
    Norm likes this.

  4. #4
    jobud9 is offline Member
    Join Date
    Dec 2011
    Posts
    34
    Rep Power
    0

    Default Re: Can I improve this code?

    very clear. how would I setup a thread? any docs?

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Can I improve this code?

    Quote Originally Posted by jobud9 View Post
    very clear. how would I setup a thread? any docs?
    Hopefully you are aware of the Oracle Java tutorials. For this type of question (for most types of new to Java questions actually), that's the first place you should look. If you're still stuck, then please feel free to come on back and ask any specific questions that you may have.

Similar Threads

  1. joptionpane quizz , improve my code ....
    By pipikrk in forum New To Java
    Replies: 6
    Last Post: 08-30-2011, 01:04 AM
  2. What can i do to improve this? Explanation please
    By biggerthanblue in forum New To Java
    Replies: 1
    Last Post: 02-19-2011, 06:55 AM
  3. Improve my GUI!
    By AJArmstron@aol.com in forum New To Java
    Replies: 8
    Last Post: 04-27-2010, 09:17 PM
  4. How to improve this code
    By Raymond in forum Advanced Java
    Replies: 9
    Last Post: 03-19-2010, 08:16 AM
  5. Replies: 16
    Last Post: 08-05-2008, 11:34 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •