Creating a C# like Asynchronous Socket
DrCataclysm
4002600 at ba-glauchau.de
Mon Nov 6 08:03:23 UTC 2017
On Sunday, 5 November 2017 at 14:47:37 UTC, DrCataclysm wrote:
> I am trying to build something like the asynchronous Sockets
> from C# .NET but I'm stuck at the accepting phase.
>
> ....
>
> The client created by _socket.accept() cannot receive any data.
>
> client.receive() immediately returns 0 like a non-blocking
> socket. I think it has something to do with the original socket
> being owned by a different thread.
>
> I am not very familiar with multitasking/multithreading in D so
> any help would be appreciated.
// I removed all multithreading and cleaned up the example. It
still does not work.
// Sockets don't seem to work as class fields, is there a reason
for this?
// Has anyone a better idea to accomplish this?
import std.socket;
import std.stdio;
void main(){
TCPListener test = new TCPListener("127.0.0.1", 9001);
test.startListening();
while (true){}
}
public class TCPListener {
ushort _port;
string _address;
bool _active;
Socket _socket = null;
Socket _connection = null;
this(string address, ushort port, string lineEnd = "\n") {
_port = port;
_address = address;
_socket = new TcpSocket();
_socket.setOption(SocketOptionLevel.SOCKET,
SocketOption.REUSEADDR, true);
}
void startListening(){
// bind the port in the main thread
try{
assert(_socket !is null);
_socket.bind(new InternetAddress(_port));
_socket.listen(3);
}
catch (Exception e){
writeln(e.msg);
}
//auto _connectionTask = task(&this.Accept);
//_connectionTask.executeInNewThread();
Accept();
}
private void Accept(){
bool error = false;
// start accepting in a different thread
try{
_connection = _socket.accept();
assert(_connection !is null); // this works
ubyte[] buffer;
// this does not block, even if the socket is
explicitly markes
// as blocking
auto receive = _connection.receive(buffer);
// this always fails
assert(receive != 0);
}
catch (SocketAcceptException e){
writeln("Error while accepting connection: " ~ e.msg);
error = true;
}
finally{
//emit(error);
}
}
}
More information about the Digitalmars-d-learn
mailing list