3

我在 Windows 上使用 D 编写了一个套接字服务器,现在我想将它移植到 Linux 上。这是代码摘要:

/*
 * this.rawsocks - SocketSet
 * this.server - Socket
 * this.clients - array of custom client worker class
 */

char[1] buff;
string input;
int nbuff = 0;

while (this.isrun) {
    this.rawsocks.add(this.server);

    if (Socket.select(this.rawsocks, null, null)) {
        if (this.rawsocks.isSet(this.server)) {
            // accepting a new connection
        }

        foreach (ref key, item; this.clients) {
            // works for all connections
            writeln("test1");

            // mystically interrupts foreach loop
            nbuff = item.connection.receive(buff);

            // works only for the first connection.
            // when the first connection is closed, it works for the next
            writeln("test2");
        }
    }

    this.rawsocks.reset();

    foreach (key, value; this.clients)
        this.rawsocks.add(value.connection);
}

item.connection.receive(buff)在 Windows 上工作正常,但在 Linux 上会中断 foreach 循环。没有任何例外,并且test2当第一个客户端断开连接时,下一个客户端正在触发。

Linux中的方法是否有一些特殊行为.receive(),或者我的实现中有一些问题?

4

1 回答 1

1

这个问题的解决方法和问题本身一样奇怪:)

foreach (ref key, item; this.clients) {
     /*
      * The solution
      * Check of client's socket activity in SocketSet queue may not be necessary in Windows, but it is necessary in Linux
      * Thanks to my friend's research of this problem
      */
     if (!this.rawsocks.isSet(item.connection)) continue;

     // works for all connections
     writeln("test1");

     // after modifying not interrupts foreach loop
     nbuff = item.connection.receive(buff);

     // after modifying also works for all connections
     writeln("test2");
}
于 2013-03-31T19:59:24.810 回答