On Thursday, 14 March 2024 at 18:49:54 UTC, Dejan Lekic wrote:
On Tuesday, 12 March 2024 at 05:13:26 UTC, zoujiaqing wrote:
How to fix it? than you ;)
Try the following:
```
class Connection
{
StreamSocketFD client;
ubyte[1024] buf = void;
// Add these two lines before the constructor:
nothrow:
@safe:
this(StreamSocketFD client)
```
Also you will need to either comment out calls to writeln() or
surround them in try/catch as writeln() may throw so it can't
really be called in nothrow code... For starters just comment
all calls to writeln() out to make it compile, and then move
from there.
This is the code I modified that can be compiled and run
successfully.
```d
import eventcore.core;
import std.functional : toDelegate;
import std.socket : InternetAddress;
import std.exception : enforce;
import core.time : Duration;
import std.stdio : writeln;
void main()
{
auto addr = new InternetAddress("127.0.0.1", 1111);
auto listener = eventDriver.sockets.listenStream(addr,
toDelegate(&onClientConnect));
enforce(listener != StreamListenSocketFD.invalid, "Failed to
listen for connections.");
writeln("Listening for requests on port 1111...");
while (eventDriver.core.waiterCount)
eventDriver.core.processEvents(Duration.max);
}
nothrow @safe: void onClientConnect(StreamListenSocketFD
listener, StreamSocketFD client, scope RefAddress)
{
import std.array: appender;
import std.algorithm: copy;
try {
writeln("onClientConnect");
Connection connection = new Connection(client);
auto w = appender!(ubyte[]);
string str = "Welcome to use my echo server.";
copy(str, w);
connection.write(w[]);
} catch (Exception e) {
// pass
}
}
class Connection
{
StreamSocketFD client;
ubyte[1024] buf = void;
nothrow:
@safe:
this(StreamSocketFD client)
{
this.client = client;
eventDriver.sockets.read(client, buf, IOMode.once, &onRead);
}
void write(ubyte[] data)
{
eventDriver.sockets.write(client, data, IOMode.all,
&onWriteFinished);
}
void onWriteFinished(StreamSocketFD fd, IOStatus status,
size_t len)
{
try {
writeln("Send size: ", len);
} catch (Exception e) {
// pass
}
}
void onRead(StreamSocketFD, IOStatus status, size_t
bytes_read)
{
if (status != IOStatus.ok)
{
try {
writeln("Client disconnect");
} catch (Exception e) {
// pass
}
eventDriver.sockets.shutdown(client, true, true);
eventDriver.sockets.releaseRef(client);
return;
}
this.write(buf[0 .. bytes_read]);
eventDriver.sockets.read(client, buf, IOMode.once, &onRead);
}
}
```