Connecting python to D on socket of localhost : target machine actively refuses connection
Enjoys Math
enjoysmath at gmail.com
Fri Sep 22 04:06:08 UTC 2017
Here's my minimal D code (server.d):
module server;
import core.thread;
import std.socket;
import std.experimental.logger;
class Server : Thread
{
private:
Socket listener;
int backlog;
string address;
ushort port;
SocketSet sockSet;
Socket[] clients;
bool running;
public:
this(ushort port, string address="") {
super(& run);
if (address == "")
address = "DESKTOP-T49RGUJ";
this.port = port;
this.address = address;
backlog = int.max;
listener = null;
running = false;
}
bool setupSocket() {
try {
listener = new Socket(AddressFamily.INET, SocketType.STREAM);
listener.bind(new InternetAddress(address, port));
sockSet = new SocketSet();
}
catch (Exception e) {
log(LogLevel.critical, e.toString());
return false;
}
return true;
}
void start() {
if (listener is null)
{
if (! setupSocket())
return;
}
running = true;
if (! isRunning) super.start();
}
void stop() {
running = false;
}
private:
void run() {
char[1024] buffer;
while(running) {
sockSet.reset();
sockSet.add(listener);
foreach (client; clients)
sockSet.add(client);
if (Socket.select(sockSet, null, null)) {
foreach (client; clients)
{
if (sockSet.isSet(client)) {
auto got = client.receive(buffer);
client.send(buffer[0 .. got]);
}
}
if (sockSet.isSet(listener)) {
auto newSocket = listener.accept();
newSocket.send("Hello!\n");
clients ~= newSocket;
}
}
}
}
}
And here's the simple python client (main.py):
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys
import socket
import settings
if __name__ == "__main__":
app = QApplication([])
window = QMainWindow()
window.show()
host = socket.gethostname()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#sock.bind((host, 0)) # have os choose random
available port
print(host)
sock.connect((host, settings.debugPort))
try:
# Send data
message = 'This is the message. It will be repeated.'
print(sys.stderr, 'sending "%s"' % message)
sock.sendall(message.encode())
# Look for the response
amount_received = 0
amount_expected = len(message)
while amount_received < amount_expected:
data = sock.recv(16)
amount_received += len(data)
print(sys.stderr, 'received "%s"' % data)
finally:
print(sys.stderr, 'closing socket')
sock.close()
sys.exit(app.exec_())
---
The client throws:
builtins.ConnectionRefusedError: [WinError 10061] No connection
could be made because the target machine actively refused it
Now, true this is python & D, but the client is generic and
minimal so bear with me.
Thanks.
I've also tried 'localhost' on both sides.
More information about the Digitalmars-d-learn
mailing list