简体   繁体   中英

Connection refused between a Python server and a Java client

The problem: I want to estabilish connection between a Python server and a Java client. The client raises an exception:

java.net.ConnectException: Connection refused: connect

Server code:

print('MOTD/name system initialized!')
        global people
        welcome = socket.socket()
        welcome.bind((socket.gethostname(), 31123))
        while True:
            welcome.listen(1)
            w, nouse = welcome.accept()
            ...
            w.send(m.strip().encode())
            w.close()

Client code:

Socket welcomesocket = new Socket("localhost", 31123);
BufferedReader motd = new BufferedReader(new InputStreamReader(welcomesocket.getInputStream()));
servs.set(i, motd.readLine());
welcomesocket.close();

The problem has to be in Java, Python - Python connection with the same circumstances works fine.

It really seems as if it's a connection problem, not really in "Java". Maybe some more info about your environment would help.

In the meantime:

If you have a telnet client, try running it like "telnet localhost 31123", this should allow to connect. Else you have something wrong with your server you're connecting to.

Regards

One problem is that the python server is binding and accepting on the IP address corresponding to the server's hostname, but the client is trying to connect to "localhost"; ie a loopback IP address.

The client needs to use the same hostname / IP address as the one that the server is binding on. And if the client and server on different machines, then you can't use "localhost" at all. (The "localhost" name typically means a 127.0.0.* loopback address. As the name suggests, a connection to a loopback address "loops back" to the host you are connecting from; ie a loopback connection won't go off the client's machine / virtual.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM