11 years ago.

TCPサーバへの接続失敗?

初めまして。 mbed NXP LPC1768 上でTCPサーバを動かしているのですが、 クライアントから接続/切断を繰り返すと5回目の接続時にacceptがtimeoutしてしまいます。

色々とググっては見たのですが特に有用な情報はないようでした。

下記のコードで再現すると思うのですが、何かまずい部分でもあるのでしょうか... ちなみに、EthernetInterfaceとrtosはいずれもmbed-officialのものを使用しています。

#include "mbed.h"
#include "EthernetInterface.h"
#include "TCPSocketServer.h"
#include "TCPSocketConnection.h"

DigitalOut myled(LED1);

EthernetInterface eth;
TCPSocketServer server;
char receiveBuf[1024];

#define PORT 1234

int main() {
    eth.init();
    eth.connect();
    printf("IP Address is %s\r\n", eth.getIPAddress());

    while(1)
    {
        printf("Binding(%d)...", PORT);
        if (server.bind(PORT) < 0) {
            printf("Could not bind server socket to port '%d'.\n\r", PORT);
            return -1;
        }
        printf("OK\r\n");
        
        printf("Listening...");
        if (server.listen() < 0) {
            printf("Could not put server socket into listening mode.\n\r");
            return -1;
        }
        printf("OK\r\n");
    
        // enable timeout.
        server.set_blocking(false);
        
        while(1)
        {
            TCPSocketConnection connection;
            bool isConnected = false;
            printf("Waiting Connect...");
            if( server.accept(connection) == 0 )
            {
                printf("Connected.\r\n");
                isConnected = true;
                connection.set_blocking(false, 10000);
                while( isConnected )
                {
                    int result = connection.receive(receiveBuf, sizeof(receiveBuf));
                    switch(result)
                    {
                    case 0:
                    case -1:
                        isConnected = false;
                        break;
                    default:
                        printf("receive %dbytes.\r\n", result);
                        break;
                    }
                }
                connection.close();
                printf("Disconnected.\r\n");
                
                // break;
            }
            else
            {
                printf("Timeout.\r\n");
            }
        }
        
        server.close();
    }    
}

36行目のset_blockingコメントアウトしてacceptでタイムアウトしないようにすると何度でも接続/切断できます。

少しTCPSocketServerのソースを見たのですが、set_blockingでタイムアウトするように設定すると、 selectで待ち受けを行うようです。これ以上は深く潜ってないのですが、何か情報ご存知の方いらっしゃいますでしょうか。

また、コード上まずそうな部分があれば、ご指摘いただけると幸いです。

1 Answer

11 years ago.

この質問は日本語フォーラム(https://mbed.org/forum/ja/topic/4367/)へ移動しましました。

Accepted Answer