ハイパー・マイコン mbedでインターネット 電子工作 3章 リスト3-1 TCPMessageBoardのプログラム  

Dependencies:   EthernetInterface TextLCD mbed-rtos mbed

main.cpp

Committer:
sunifu
Date:
2014-07-09
Revision:
0:2809bb7303a8

File content as of revision 0:2809bb7303a8:

#include "mbed.h"
#include "EthernetInterface.h"
#include "TextLCD.h" 

#define MESSAGEBOARD_SERVER_PORT   55555

TextLCD lcd(p24, p26, p27, p28, p29, p30); 

int main() {
    int stat;
    EthernetInterface eth;
 
    lcd.cls();
    
    // USE DHCP
    eth.init();
    // Use Static IP
    //eth.init("192.168.0.9","255.255.255.0","192.168.0.1");

    stat = eth.connect();

    lcd.locate(0,1);
    printf("\r\n");   
    if ( stat == 0 ){
        printf("IPAddress[%s]\r\n",eth.getIPAddress());
        lcd.printf("%s",eth.getIPAddress());
    }else{
        printf("DHCP Error...\r\n");
        lcd.printf("DHCP Error!");
        exit(-1);
    }
    
    TCPSocketServer server;
    server.bind(MESSAGEBOARD_SERVER_PORT);
    server.listen();
    
    while (true) {
    
        printf("Wait for new connection...\r\n");
        TCPSocketConnection client;
        server.accept(client);
        
        printf("Connection from: %s\r\n", client.get_address());
        char buffer[17];
        while (true) {
            int n = client.receive(buffer, sizeof(buffer));
            
            buffer[n]='\0';
            if ( !client.is_connected() ){
                printf("Disconnection...\r\n");
                break;
            }
            lcd.locate(0,0);
            lcd.printf("                ");
            if ( n > 0 ){     
                lcd.locate(0,0);
                lcd.printf("%s",buffer);      
                printf("Send Character[%d:%s]\r\n",n,buffer);
            }
            else{
                printf("[0]-\r\n");
            }     
        }        
        client.close();
    }
}