CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 2010
    Posts
    2

    TCP Server on embedded system

    Hi...I've been working on a TCP Server for an embedded system (TINI board). It can serve basic webpages and some error codes (like 404). I need it to handle images too and I can't seem to get it working. Does anyone have any good tutorial links I can look at? I've been Googleing a lot and can't seem to find anything that works.

    Here's my code if anyone wants to take a look. It's based on some example code designed for the TINI board that I've modified. Sorry for the length and thanks for any input.

    Code:
    package realtimewebpage;
    import java.io.*;
    import java.net.*;
    
    public class RealTimeWebPage implements Runnable {
    
      private ServerSocket server;
      private int readTimeout;
      private Thread serverThread;
      private volatile boolean runServer;
    
      /**
       * Main method that tests the class.
       */
    
      public static void main(String[] args) throws IOException {
    
        // The port clients will connect on.
        // Port 80 is the default for HTTP requests.
        int localPort = 80;
    
        // The timeout in milliseconds to wait for a request from a client
        // after connecting.
        int readTimeout = 5000;
    
        // Create a RealTimeWebPage object using localPort and readTimeout.
        RealTimeWebPage server = new RealTimeWebPage(localPort, readTimeout);
    
        while (true){
    
          // Endless loop that executes while waiting for connections.
          try {
    
            // The thread can spend most of its time sleeping.
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            System.out.print("InterruptedException: ");
            System.out.println(e.getMessage() );
          }
        } // end while(true)
      } // end main
    
      /**
       * Creates a thread to handle connection requests.
       *
       * @param localPort the port to listen for connections on.
       * @param readTimeout the time in milliseconds to wait for bytes from a remote host.
       *
       * @throws IOException on error in opening the server socket.
       */
      public RealTimeWebPage(int localPort, int readTimeout) throws IOException {
    
        // Create a server socket on localPort.
        // The ServerSocket object creates a socket object on receiving a
        // communication request.
        server = new ServerSocket(localPort);
        System.out.println("The server is listening on port " + localPort + ".");
    
        // serverThread uses the passed readTimeout value.
        this.readTimeout = readTimeout;
    
        // Create a thread to handle connection requests.
        serverThread = new Thread(this);
    
        // A Daemon thread ends when no user (non-Daemon) threads are running.
        serverThread.setDaemon(true);
    
        // The start() method calls the thread's run() routine.
        serverThread.start();
      } // end RealTimeWebPage constructor
    
      /**
       * Provides a way to stop the server under program control.
       */
      public void stopServer() {
    
        // When runServer is false, the run method ends.
        runServer = false;
        try {
    
          // Close the socket, ignoring exceptions.
          server.close();
        } catch (IOException e) {
        }
      } // end stopServer
    
      /**
       * Main method for the thread.
       * Accepts connections and calls a routine to handle each connection.
       */
      public void run() {
    
        // runServer remains true until an exception or the stop method sets it false.
        runServer = true;
    
        while (runServer) {
          try {
    
            // Wait for and accept a connection request.
            Socket socket = server.accept();
    
            try {
    
              // Call a method to handle the connection
              handleConnection(socket);
    
            } catch (IOException e) {
              System.out.print("IOException: ");
              System.out.println(e.getMessage());
            } finally {
    
              // Close the socket to release resources.
              // Ignore exceptions.
              try {
                socket.close();
              } catch (IOException e) {
              }
            }
          } catch (IOException e) {
    
            // There was an error while accepting a new socket.
            // Stop the server thread.
            runServer = false;
          }
        } // end while(runServer);
      } // end run
    
      /**
       * Handles a single conection.
       *
       * @param socket the connected socket
       *
       * @throws IOException on error when communicating with the remote
       *         host.
       */
      private void handleConnection(Socket socket) throws IOException {
    
        System.out.println("Connected to " + socket);
    
        // Set the read timeout for waiting for data from the remote host.
        socket.setSoTimeout(readTimeout);
    
        // An InputStream object reads data from the remote host.
        InputStream in = socket.getInputStream();
    
        // A Printstream object writes to the remote host.
        PrintStream out = new PrintStream(socket.getOutputStream());
    
        try {
    
          // Call a method to process a received request, passing the input
          // and output stream objects to use in communicating with the remote host.
          processRequest(in, out);
    
          // checkError also flushes the output stream to send the data immediately.
           if (out.checkError()) {
            System.out.println("An error occurred while sending a web page.");
          } else {
            System.out.println("A response was sent.");
          }
        } catch (InterruptedIOException e) {
          System.out.print("InterruptedIOException: ");
          System.out.println(e.getMessage());
          System.out.print("The connection timed out after receiving no data for : ");
          System.out.print(readTimeout / 1000);
          System.out.println(" seconds.");
        }
      } // end handleConnection
    
      /**
       * Processes an HTTP request.
       *
       * @param in an InputStream object
       * @param out a PrintStream object
       *
       * @throws IOException if there was an error communicating with the remote
       *         host.
       */
      private void processRequest(InputStream in, PrintStream out)
          throws IOException {
    
        // Read the first four received bytes.
        int b1 = in.read();
        int b2 = in.read();
        int b3 = in.read();
        int b4 = in.read();
    
        // This server supports GET requests only.
        // GET must be upper case.
        // Find out if the received bytes = "GET "
        if (('G' == b1) && ('E' == b2) && ('T' == b3) && (' ' == b4)) {
    
          // If yes, read any following bytes and store them in a String buffer.
          // Stop reading on detecting a space, a new-line or line-feed character
          // ('\r', '\n'), or and end-of-file marker (-1).
          StringBuffer requestBuffer = new StringBuffer();
          int b = in.read();
          while ((b != -1) && (b != ' ') && (b != '\r') && (b != '\n')) {
            requestBuffer.append((char)b);
            b = in.read();
          }
    
          // Convert the StringBuffer to a String to enable examining its contents.
          String requestedPage = requestBuffer.toString();
    
          // The server returns its real-time web page on receiving a request for
          // the default page or for /index.html.
          String defaultPage = "/";
          String indexPage = "/index.html";
          requestedPage=".".concat(requestedPage);
          if(requestedPage.equals("./")){
              requestedPage="./index.html";
          }
          //String fixedPage;
          //requestedPage.getChars(1, 100, fixedPage, 0);
    
          File fresource = new File(requestedPage);
          if (fresource.exists() || requestedPage.equals(defaultPage)) {
    
    
            // Call a routine to return the real-time web page.
            sendWebPage(out, requestedPage);
    
          } else {
    
            // If the requested file doesn't match a supported file name,
            // return an error page with error code 404.
            sendErrorPage(out, "404 Not Found");
          }
    
        } else {
    
          // "GET " wasn't received.
          // If -1 was returned, the input stream is closed, so do nothing.
          // For any other received data, return an error page with error code 501.
          if ((b1 | b2 | b3 | b4) != -1) {
            sendErrorPage(out, "501 Not Implemented");
          }
        } // end  if ('G' == b1 || 'E' == b2 || 'T' == b3 || ' ' == b4)
      } // end processRequest
    
      /**
       * Sends the web page containing real-time data.
       *
       * @param out a PrintStream object
       *
       * @throws IOException if there was an error sending the page.
       */
      private void sendWebPage(PrintStream out, String Page) throws IOException {
        File fresource = new File(Page);
        FileInputStream IndexWebPage = new FileInputStream(fresource);
    
        // Send the response's start line and headers
        out.print("HTTP/1.0 200 OK\r\n"
                  + "Content-Type: text/html\r\n"
                  + "\r\n");
        if(fresource.exists()){
        byte [] http_byte= new byte[200];
        IndexWebPage.read(http_byte);
    
    
        out.write(http_byte);
        }else{
            out.print("File Not Found");
        }
    
      }
    
      /**
       * Sends an error page with the specified error message.
       *
       * @param out a PrintStream object
       * @param errorMessage the page's error message
       *
       * @throws IOException if there was an error sending the page.
       */
      private void sendErrorPage(PrintStream out, String errorMessage)
          throws IOException
      {
        // Send the response's start line and headers.
        out.print("HTTP/1.0 ");
        out.print(errorMessage);
        out.print("\r\n"
                  + "Content-Type: text/html\r\n"
                  + "\r\n");
    
        // Send the error message.
        out.print("<html>"
                  + "<head><title>");
        out.print(errorMessage);
        out.print("</title></head>"
                  + "<body>"
                  + "<h1>");
        out.print(errorMessage);
        out.print("</h1>"
                  + "</body>"
                  + "</html>");
      } // end sendErrorPage
    
    } // end RealTimeWebPage class

  2. #2
    Join Date
    Apr 2010
    Posts
    2

    Re: TCP Server on embedded system

    I've rewritten part of the above code in an attempt to clean it up and get it to do what I need.

    Code:
    package TCPServer;
    
    import java.io.*;
    import java.net.*;
    
    /**
     * TCP server that receives a single byte, increments the value, and
     * sends the incremented value back.
     *
     * This file and other embedded Ethernet and Internet code and resources are
     * available from www.Lvr.com.
     *
     * @author Jan Axelson
     * @author Shawn Silverman
     */
    
    public class TcpServer implements Runnable {
    
      private ServerSocket server;
      private int readTimeout;
      private Thread serverThread;
      private volatile boolean runServer;
    
      /**
       * Main method that tests the class.
       */
      public static void main(String[] args) throws IOException {
    
        // The port that clients will connect on.
        int localPort = 5551;
    
        // The timeout in milliseconds to wait for data from a client
        // after connecting.
        int readTimeout = 5000;
    
        // Create a TcpServer object using localPort and readTimeout.
        TcpServer myTcpServer = new TcpServer(localPort, readTimeout);
    
        while (true){
    
          // Endless loop that executes while waiting for connections.
          try {
    
            // The thread can spend most of its time sleeping.
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            System.out.print("InterruptedException: ");
            System.out.println(e.getMessage() );
          }
        } // end while(true)
      } // end main()
    
      /**
       * Creates a thread to handle connection requests.
       *
       * @param localPort the port to listen for connections on.
       * @param readTimeout the time in milliseconds to wait for bytes from a remote host.
       * @throws IOException on error in opening the server socket.
       */
      public TcpServer(int localPort, int readTimeout) throws IOException {
    
        // Create a server socket on localPort.
        // The ServerSocket object creates a socket object on receiving a
        // communication request.
        server = new ServerSocket(localPort);
    
        // The serverThread thread uses the readTimeout value passed to this constuctor.
        this.readTimeout = readTimeout;
    
        // Create a thread to handle connection requests.
        serverThread = new Thread(this);
    
        // The thread is a Daemon thread, which ends when no user (non-Daemon)
        // threads are running.
        serverThread.setDaemon(true);
    
        // The start() method calls the thread's run() routine.
        serverThread.start();
      } // end TcpServer constructor
    
      /**
       * Stops the server.
       */
      public void stop() {
    
        // When runServer is false, the run method ends.
        runServer = false;
    
        try {
          // Close the socket. Do nothing on an exception.
          server.close();
        } catch (IOException e) {
        }
      } // end stop()
    
      /**
       * Main method for the thread.
       */
      public void run() {
    
        // runServer remains true until an exception or the stop() method sets it false.
        runServer = true;
    
        while (runServer) {
          try {
            // Wait for and accept a connection request.
            Socket socket = server.accept();
    
            try {
              // Call a method to handle the connection.
              handleConnection(socket);
    
            } catch (IOException e) {
              System.out.print("Error while working with socket: ");
              System.out.println(e.getMessage());
            } finally {
    
              // Close the socket to release resources.
              // Do nothing on an exception.
              try {
                socket.close();
              } catch (IOException e) {
              }
            }
          } catch (IOException e) {
    
            // There was an error while accepting a new socket.
            // Stop the server thread.
            runServer = false;
          }
        } // end while (runServer)
      } // end run()
    
      /**
       * Handles a single conection.
       *
       * @param socket a connected socket
       * @throws IOException on error when communicating with the remote
       *         host.
       */
      private void handleConnection(Socket socket) throws IOException {
    
        // Set the read timeout for waiting for data from the remote host.
        socket.setSoTimeout(readTimeout);
    
        // An InputStream object reads data from the remote host.
        InputStream in = socket.getInputStream();
    
        // An Outputstream object writes to the remote host.
        OutputStream out = socket.getOutputStream();
    
        try {
    
          // Try to read a byte from the remote host.
          int b = 0;
          while (in.available()==0)
          {
              b=0;
          }
          b=in.available();
          byte[] http_request = new byte[b];
    
          in.read(http_request);
          String info = new String (http_request);
    
          System.out.println("Received: ");
          System.out.print(info);
          if(info.substring(0, 3).equals("GET"))
          {
          System.out.println("Sent: ");
          byte[] response="HTTP/1.1 200 OK\r\n\r\n<HTML><BODY>SIMPLE WEB PAGE</BODY></HTML>".getBytes();
          out.write(response);
          String write = new String (response);
          System.out.println(write);
          }
    
          else
          {
              byte[] BadForm = "HTTP/1.1 400 Bad Request\r\n\r\n".getBytes();
              out.write(BadForm);
              String error = new String (BadForm);
              System.out.println(error);
          }
          out.flush();
            out.close();
    
        } catch (InterruptedIOException ex) {
    
          // The read attempt has timed out.
          System.out.print("The remote host sent no data within ");
          System.out.print(readTimeout / 1000);
          System.out.println(" seconds.");
        }
      } // end handleConnection()
    } // end TcpServer class

  3. #3
    Join Date
    Mar 2010
    Posts
    74

    Re: TCP Server on embedded system

    This one?
    http://www.java2s.com/Code/Java/Tiny...HttpServer.htm

    I did something like prototype for HTTP server,
    only problem with images that you have recognize request for image from client,
    and send image like html page.

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured