Problem with two servers

Hello guys . I’m trying to make a multiple server. I want to access on 192.168.0.120:80 a page and an another 192.168.0.120:8080 another page that is stocked on my SD card. I don’t want to access them simoultaneous.The code compiles and whent i want to access the browser and enter the ip and port he don’t show me nothing. Can anyone help me?

The first part of the code:

#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <Ethernet.h>
#include <serialGLCD.h>

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x2F, 0xDC };
byte ip[] = { 192,168,0, 120 };
char rootFileName[] = "login.htm"; 

EthernetServer server(80);
EthernetServer server2(8080);


//pagina contact

// String variables fo each line on the LCD declared globally because I'm lazy, but also
// because it needs to survive loop(), without being cleared from the stack (also to hell with good practice)
String line1 = "                ";
String line2 = "                ";


// Constant strings for rendering the Webpage are stored in flash 
// memory to ration it for other non constant variables

// Strings stored in flash mem for the Html Header
prog_char Header_0[] PROGMEM = "HTTP/1.1 200 OK";            //
prog_char Header_1[] PROGMEM = "Content-Type: text/html";    //
prog_char Header_2[] PROGMEM = "";                           //
prog_char Header_3[] PROGMEM = "<HTML>\n<HEAD>";             // The header lines
prog_char Header_4[] PROGMEM = "<TITLE>Contact</TITLE>"; //
prog_char Header_5[] PROGMEM = "</HEAD><BODY>";              //

// A table of pointers to the flash memory strings for the header
PROGMEM const char *Header_table[] =
{   
  Header_0,
  Header_1,
  Header_2,
  Header_3,
  Header_4,
  Header_5};

// Strings stored in flash mem for the body of the webpage, including the input forms
// Only the longer lines, not involving variables are stored here
prog_char Body_0[] PROGMEM = "<H2>Ce se afiseaza :</H2>";            
prog_char Body_1[] PROGMEM = "<H2>Trimite un mesaj pe LCD!</H2>";    
prog_char Body_2[] PROGMEM = "<form action=\"/?\" method=get>";                           
prog_char Body_3[] PROGMEM = "<b>Nume: </b><input type=\"text\" name=\"L1\" maxlength=\"16\" size=\"16\" />
";            
prog_char Body_4[] PROGMEM = "<b>Mesaj: </b><input type=\"text\" name=\"L2\" maxlength=\"16\" size=\"16\" />
"; 
prog_char Body_5[] PROGMEM = "<input type=\"submit\" value=\"Trimite\" /></form>";              

// A table of pointers to the flash memory strings for the body
PROGMEM const char *Body_table[] =
{   
  Body_0,
  Body_1,
  Body_2,
  Body_3,
  Body_4,
  Body_5};

// Begin Webserver Specific Code

// Print out MIME and HTML header at top of webpage using the
// strings previously stored in flash memory
void HtmlHeader(EthernetClient client) {
  
    char buffer[30]; //A character array to hold the strings from the flash mem
    
    for (int i = 0; i < 6; i++) {
      strcpy_P(buffer, (char*)pgm_read_word(&(Header_table[i]))); // Necessary casts and dereferencing, just copy. 
      client.println( buffer );
    }
}
 
// Print the footer at the bottom of the webpage
void HtmlFooter(EthernetClient client) {
    client.println("</BODY></HTML>");
}
 
 
// Parse an HTTP request header one character at a time, seeking string variables (modified from Kevin Haw's code)
void ParseHttpHeader(EthernetClient &client) {
    char c;
    int i = 0;    //An integer use to limit the size of rawUrlText (prevents crashing due to running out of memory)
    String rawUrlText = "";
 
    // Skip through until we hit a question mark (first one)
    while((c = client.read()) != '?' && client.available()) {
      // Debug - print data
      Serial.print(c);
    }
    
    // Are we here for a question mark or did we run out of data?
    if(client.available() > 2) {
 
      // Read the data and add it to our unmodified string rawURLText! 
      // the incrementer limits the input to about 1 line of plain text and 1/2 line of symbols, more causes line2 to truncate
      while((c = client.read()) != ' ' && client.available() && i < 55) {
          rawUrlText = rawUrlText + c;
          Serial.print(c);
          i++;
      }
      
      htmlToHuman(rawUrlText);            // Make it readable
      line1.setCharAt(line1.lastIndexOf('0'), ' '); // the lcd prints the 0's in the null terminator, so we remove them
      line2.setCharAt(line2.lastIndexOf('0'), ' '); //This has been revised to prevent remove of legit 0's
      
    }   
  return;
}

// A function that takes the html formatted string and makes it readable again
void htmlToHuman(String URLstring) {

    int indexOfDelim = 0;  //This variable stores the location of our delimiter so we can find where line1 ends and line2 begins
    
    // The following array stores a list of ugly html codes, and the special charaters they represent (for changing them back)
    const String CHAR_CONVERSIONS[29][2] = {{"+"," "},{"%40","@"},{"%23","#"},{"%24","$"},{"%2B","+"},{"%21","!"},{"%7E","~"},
                                            {"%3A",":"},{"%3B",";"},{"%2C",","},{"%3F","?"},{"%2F","/"},{"%7C","|"},{"%5E","^"},
                                            {"%5C","\\"},{"%7B","{"},{"%7D","}"},{"%5B","["},{"%5D","]"},{"%3C","<"},{"%3E",">"},
                                            {"%28","("},{"%29",")"},{"%27","'"},{"%22","\""},{"%3F","?"},{"%26","&"},{"%3D","="},
                                            {"%25","%"}};
    
    URLstring.replace("L1=","");     // remove the unecessary field variable names
    URLstring.replace("&L2=","`");   // and turn this one into our delimiter character ` (The one on the ~ key)
    
    //A for loop that replaces all the html codes with the right symbols
    for (int i=0 ; i < 29; i++) {
      URLstring.replace(CHAR_CONVERSIONS[i][0],CHAR_CONVERSIONS[i][1]);
    }
    
    indexOfDelim = URLstring.indexOf("`");       // find the index of that delimiter
    
    line1 = URLstring.substring(0,indexOfDelim); // set line1 and line 2 using that knowlege
    line1 += NULL;                               // but add a null terminator to each to avoid some odd bugs
    line2 = URLstring.substring(indexOfDelim+1,URLstring.length());
    line2 += NULL;

    serialGLCD lcd;
    lcd.clearLCD();
    delay(40);
    lcd.gotoPosition(5,5);
    Serial.print("Ai primit un mesaj de la :");
    lcd.gotoPosition(20,15);
    Serial.print(line1);
    lcd.gotoPosition(5,25);
    Serial.print("Continut mesaj");
    lcd.gotoPosition(20,35);
    Serial.print(line2);
    delay(10000);
    return;
}
//terminare pagina contact

char* ficheiroLer;
/************ SDCARD STUFF ************/
Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;

// store error strings in flash to save RAM
#define error(s) error_P(PSTR(s))

void error_P(const char* str) {
  PgmPrint("error: ");
  SerialPrintln_P(str);
  if (card.errorCode()) {
    PgmPrint("SD error: ");
    Serial.print(card.errorCode(), HEX);
    Serial.print(',');
    Serial.println(card.errorData(), HEX);
  }
  while(1);
}

void setup() {
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
   PgmPrint("Free RAM: ");
  Serial.println(FreeRam());  
  
  // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
  // breadboards.  use SPI_FULL_SPEED for better performance.
  pinMode(10, OUTPUT);                       // set the SS pin as an output (necessary!)
  digitalWrite(10, HIGH);                    // but turn off the W5100 chip!

  if (!card.init(SPI_HALF_SPEED, 4)) error("card.init failed!");
  
  // initialize a FAT volume
  if (!volume.init(&card)) error("vol.init failed!");

  PgmPrint("Volume is FAT");
  Serial.println(volume.fatType(),DEC);
  Serial.println();
  
  if (!root.openRoot(&volume)) error("openRoot failed");

  // list file in root with date and size
  PgmPrintln("Files found in root:");
  root.ls(LS_DATE | LS_SIZE);
  Serial.println();
    
  // Recursive list of all directories
  PgmPrintln("Files found in all dirs:");
  root.ls(LS_R);
  
  Serial.println();
  PgmPrintln("Done");

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  server2.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

The second part of the code

#define BUFSIZ 100

void loop() {
  
// client 1  
// check port 80
  EthernetClient client = server.available();
 
  boolean bPendingHttpResponse = false; // True when we've received a whole HTTP request and need to output the webpage
  boolean bPreventSecondParse = false;  //Stops a second successive run of parseHttpHeader(), this prevents some nasty bugs.
  char c;  // For reading in HTTP request one character at a time
 
  if(client)
{
    // Loop as long as there's a connection
    while (client.connected()) {
      // Do we have pending data (an HTTP request) and is this the first parse?    
      if (client.available() && !bPreventSecondParse) {
 
        // Indicate we need to respond to the HTTP request as soon as we're done processing it
        bPendingHttpResponse = true;
        bPreventSecondParse = true;
        
        ParseHttpHeader(client);  
      }
      else {
        // There's no data waiting to be read in on the client socket.  Do we have a pending HTTP request?
        if(bPendingHttpResponse) {
          // Yes, we have a pending request.  Clear the flag and then send the webpage to the client
          bPendingHttpResponse = false;
          bPreventSecondParse = false; 
 
          // send a standard http response header and HTML header
          HtmlHeader(client);
 
          // The following code Sends the relevant Html to the connected connected client to render the web page
          /* For readability, the Html sent to the client is as follows (the second and third lines are not stored in flash memory)
           *"<H2>Currently Displayed:</H2>"
           *"<b>Line 1:</b> " + line1 + "
"        
           *"<b>Line 2:</b> " + line2 + "

" 
           *"<H2>Change it to something else!</H2>"
           *"<form action=\"/?\" method=get>"
           *"<b>Line 1: </b><input type=\"text\" name=\"L1\" maxlength=\"16\" size=\"16\" />
"
           *"<b>Line 2: </b><input type=\"text\" name=\"L2\" maxlength=\"16\" size=\"16\" />
"
           *"<input type=\"Trimite\" value=\"Trimite\" /></form>"
           */
           
          char buffer[90]; //A character array to hold the strings from the flash mem
          
          strcpy_P(buffer, (char*)pgm_read_word(&(Body_table[0])));        // gets and prints the first line
          client.println( buffer );
          client.println("<b>Nume :</b> " + line1 + "
");            // manually print the lines involving variables
          client.println("<b>Mesaj :</b> " + line2 + "

");
          for(int i = 1; i < 6; i++) {                                     // Use a for loop to print the remaining lines
            strcpy_P(buffer, (char*)pgm_read_word(&(Body_table[i])));
            client.println( buffer );
          }
          
          // send HTML footer
          HtmlFooter(client);
 
          // give the web browser time to receive the data
          delay(1);
          client.stop();
        }
      }
    }  // End while(connected)
}
//terminare if(client)  
 
 client = server2.available();
  //client 2
  char clientline[BUFSIZ];
  char *filename;
  int index = 0;
  int image = 0;
  // listen for incoming clients
  if (client) {
    // an http request ends with a blank line
    boolean current_line_is_blank = true;
    
    // reset the input buffer
    index = 0;
    
      while (client.connected()) {
        if (client.available()) {
          char c = client.read();
          
        // If it isn't a new line, add the character to the buffer
        if (c != '\n' && c != '\r') {
          clientline[index] = c;
          index++;
          // are we too big for the buffer? start tossing out data
          if (index >= BUFSIZ) 
            index = BUFSIZ -1;
            
          // continue to read more data!
          continue;
        }
          
        // got a \n or \r new line, which means the string is done
        clientline[index] = 0;
        filename = 0;
        
        // Print it out for debugging
        Serial.println(clientline);
        
        // Look for substring such as a request to get the root file
        if (strstr(clientline, "GET / ") != 0) {
          filename = rootFileName;
        }
        if (strstr(clientline, "GET /") != 0) {
          // this time no space after the /, so a sub-file
          
          if (!filename) filename = clientline + 5; // look after the "GET /" (5 chars)
          // a little trick, look for the " HTTP/1.1" string and 
          // turn the first character of the substring into a 0 to clear it out.
          (strstr(clientline, " HTTP"))[0] = 0;
          
          // print the file we want
          Serial.println(filename);
          
          if (! file.open(&root, filename, O_READ)) {
            client.println("HTTP/1.1 404 Not Found");
            client.println("Content-Type: text/html");
            client.println();
            client.println("<h2>File Not Found!3</h2>");
            break;
          }
          
          Serial.println("Opened!");
          
          client.println("HTTP/1.1 200 OK");
          if (strstr(filename, ".htm") != 0)
             client.println("Content-Type: text/html");
         else if (strstr(filename, ".css") != 0)
             client.println("Content-Type: text/css");
         else if (strstr(filename, ".png") != 0)
             client.println("Content-Type: image/png");
          else if (strstr(filename, ".jpg") != 0)
             client.println("Content-Type: image/jpeg");
         else if (strstr(filename, ".gif") != 0)
             client.println("Content-Type: image/gif");
         else if (strstr(filename, ".3gp") != 0)
             client.println("Content-Type: video/mpeg");
         else if (strstr(filename, ".pdf") != 0)
             client.println("Content-Type: application/pdf");
         else if (strstr(filename, ".js") != 0)
             client.println("Content-Type: application/x-javascript");
         else if (strstr(filename, ".xml") != 0)
             client.println("Content-Type: application/xml");
         else 
             client.println("Content-Type: text");
          client.println();
        
//data transfer           
           byte clientBuf[64];
           int clientCount = 0;
           while(file.available()) 
           {
           clientBuf[clientCount] = file.read();
           clientCount++;
        if (clientCount > 63) 
        {
        client.write(clientBuf, 64);
        clientCount = 0;
      }
    }
    if (clientCount > 0) {
      client.write(clientBuf, clientCount);
    }
    file.close();
    memset(&filename, 0, sizeof(filename));
  }         
  else {
          // everything else is a 404
          client.println("HTTP/1.1 404 Not Found");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<h2>File Not Found!</h2>");
           }
        break;
      }
        }
    // give the web browser time to receive the data
    delay(1);
    client.stop();
  }
  
}

Try this to get started. It doesn’t use the SD yet, but you can add that later.

#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// change to your network settings
IPAddress ip( 192,168,2,2 );
IPAddress gateway( 192,168,2,1 );
IPAddress subnet( 255,255,255,0 );

EthernetServer server(80);
EthernetServer server2(8080);

void setup()
{
  Serial.begin(9600);

  // disable w5100 while setting up SD
  pinMode(10,OUTPUT);
  digitalWrite(10,HIGH);

  Serial.print(F("Starting SD.."));
  if(!SD.begin(4)) Serial.println(F("failed"));
  else Serial.println(F("ok"));
  
  Ethernet.begin(mac, ip, gateway, gateway, subnet);
  digitalWrite(10,HIGH);

  delay(2000);
  server.begin();
  server2.begin();
  Serial.println(F("Ready"));
}

void loop()
{
  EthernetClient client = server.available();
  if(client) {
    boolean currentLineIsBlank = true;
    boolean currentLineIsGet = true;
    int tCount = 0;
    char tBuf[64];
    int r,t;
    char *pch;
    IPAddress ipBuf;
    
    Serial.print(F("Client request: "));
    
    while (client.connected()) {
      while(client.available()) {
        char c = client.read();

        if(currentLineIsGet && tCount < 63)
        {
          tBuf[tCount] = c;
          tCount++;
          tBuf[tCount] = 0;          
        }

        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response
          Serial.println(tBuf);
          Serial.print(F("POST data: "));
          while(client.available()) Serial.write(client.read());
          Serial.println();
          
          pch = strtok(tBuf,"?");

          while(pch != NULL)
          {
            if(strncmp(pch,"t=",2) == 0)
            {
              t = atoi(pch+2);
              Serial.print(F("t="));
              Serial.println(t,DEC);             
            }

            if(strncmp(pch,"r=",2) == 0)
            {
              r = atoi(pch+2);
              Serial.print(F("r="));              
              Serial.println(r,DEC);
            }


            pch = strtok(NULL,"& ");
          }
          Serial.println(F("Sending response"));
          client.println(F("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n<html>"));
          client.println(F("<body><H1>TEST</H1>"));
          client.println(F("<form method=GET>T: <input type=text name=t>
"));
          client.println(F("R: <input type=text name=r>
<input type=submit></form>"));
          client.println(F("</body></html>\r\n"));
          client.stop();
        }
        else if (c == '\n') {
          currentLineIsBlank = true;
          currentLineIsGet = false;
        } 
        else if (c != '\r') {
          currentLineIsBlank = false;
        }
      }
    }
    Serial.println(F("done"));
  }

  client = server2.available();
  if(client) {
    Serial.println(F("Server2"));

    boolean currentLineIsBlank = true;
    boolean currentLineIsGet = true;
    int tCount = 0;
    char tBuf[64];
    int r,t;
    char *pch;
    IPAddress ipBuf;
    
    Serial.print(F("Client request: "));
    
    while (client.connected()) {
      while(client.available()) {
        char c = client.read();

        if(currentLineIsGet && tCount < 63)
        {
          tBuf[tCount] = c;
          tCount++;
          tBuf[tCount] = 0;          
        }

        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response
          Serial.println(tBuf);
          Serial.print(F("POST data: "));
          while(client.available()) Serial.write(client.read());
          Serial.println();
          
          Serial.println(F("Sending response"));
          client.println(F("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n<html>"));
          client.println(F("<body><H1>TEST Server 2</H1>"));
          
          client.println(F("</body></html>\r\n"));
          client.stop();
        }
        else if (c == '\n') {
          currentLineIsBlank = true;
          currentLineIsGet = false;
        } 
        else if (c != '\r') {
          currentLineIsBlank = false;
        }
      }
    }
    Serial.println(F("done"));
  }
}

ok, thanks , i'll give it a try.

it works but when i atach those things with sdfat and sdfatutil library it dosen’t work , do you know how to fix this ?

danyel_0016:
it works but when i atach those things with sdfat and sdfatutil library it dosen't work , do you know how to fix this ?

"...it doesn't work." Can you make that any more vague? If you are using an Uno, you may be running out of SRAM.

sorry , I mean that the program you gave me works and what I atached did not work. Yes I have arduino Uno , do I have any chance to resolve this problem?

I need more than "it doesn't work". Where does it fail? On startup? When it gets a request? When it opens a file? If you are not sure, put stuff like this at or near code where it is failing.

Serial.println(F("I'm here #1"));

this code i have with what you gave to me , sorry because i’m new to this but i need to finish this project.

ms.txt (14.9 KB)

The code you have in that attached file isn't even close to what I gave you. I never use the String data type.

Maybe you should select a simpler project next time. Two servers on one Arduino is a feat in itself. Most here have trouble with one. Search the forum for two servers on one Arduino. How many do you find?

only one question , with the code i have in the first post, can i make it work or the arduino don't have power to make what i want ? thanks.