Вопрос-ответ

java.net.ConnectException: Connection refused

java.net.ConnectException: отказано в подключении

Я пытаюсь реализовать TCP-соединение, со стороны сервера все работает нормально, но когда я запускаю клиентскую программу (с клиентского компьютера) Я получаю следующую ошибку:

java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at TCPClient.main(TCPClient.java:13)

Я пытался изменить номер сокета на случай, если он использовался, но безрезультатно, кто-нибудь знает, что вызывает эту ошибку и как ее исправить.

Код сервера:

//TCPServer.java

import java.io.*;
import java.net.*;

class TCPServer {
public static void main(String argv[]) throws Exception {
String fromclient;
String toclient;

ServerSocket Server = new ServerSocket(5000);

System.out.println("TCPServer Waiting for client on port 5000");

while (true) {
Socket connected = Server.accept();
System.out.println(" THE CLIENT" + " " + connected.getInetAddress()
+ ":" + connected.getPort() + " IS CONNECTED ");

BufferedReader inFromUser = new BufferedReader(
new InputStreamReader(System.in));

BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connected.getInputStream()));

PrintWriter outToClient = new PrintWriter(
connected.getOutputStream(), true);

while (true) {

System.out.println("SEND(Type Q or q to Quit):");
toclient = inFromUser.readLine();

if (toclient.equals("q") || toclient.equals("Q")) {
outToClient.println(toclient);
connected.close();
break;
} else {
outToClient.println(toclient);
}

fromclient = inFromClient.readLine();

if (fromclient.equals("q") || fromclient.equals("Q")) {
connected.close();
break;
} else {
System.out.println("RECIEVED:" + fromclient);
}

}

}
}
}

Клиентский код:

//TCPClient.java

import java.io.*;
import java.net.*;

class TCPClient {
public static void main(String argv[]) throws Exception {
String FromServer;
String ToServer;

Socket clientSocket = new Socket("localhost", 5000);

BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
System.in));

PrintWriter outToServer = new PrintWriter(
clientSocket.getOutputStream(), true);

BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));

while (true) {

FromServer = inFromServer.readLine();

if (FromServer.equals("q") || FromServer.equals("Q")) {
clientSocket.close();
break;
} else {
System.out.println("RECIEVED:" + FromServer);
System.out.println("SEND(Type Q or q to Quit):");

ToServer = inFromUser.readLine();

if (ToServer.equals("Q") || ToServer.equals("q")) {
outToServer.println(ToServer);
clientSocket.close();
break;
} else {
outToServer.println(ToServer);
}
}
}
}
}
Переведено автоматически
Ответ 1

This exception means that there is no service listening on the IP/port you are trying to connect to:


  • You are trying to connect to the wrong IP/Host or port.

  • You have not started your server.

  • Your server is not listening for connections.

  • On Windows servers, the listen backlog queue is full.

Ответ 2

I would check:


  • Host name and port you're trying to connect to

  • The server side has managed to start listening correctly

  • There's no firewall blocking the connection

The simplest starting point is probably to try to connect manually from the client machine using telnet or Putty. If that succeeds, then the problem is in your client code. If it doesn't, you need to work out why it hasn't. Wireshark may help you on this front.

Ответ 3

One point that I would like to add to the answers above is my experience-

"I hosted on my server on localhost and was trying to connect to it through an android emulator by specifying proper URL like http://localhost/my_api/login.php . And I was getting connection refused error"

Point to note - When I just went to browser on the PC and use the same URL (http://localhost/my_api/login.php) I was getting correct response

so the Problem in my case was the term localhost which I replaced with the IP for my server (as your server is hosted on your machine) which made it reachable from my emulator on the same PC.


To get IP for your local machine, you can use ipconfig command on cmd
you will get IPv4 something like 192.68.xx.yy
Voila ..that's your machine's IP where you have your server hosted.
use it then instead of localhost

http://192.168.72.66/my_api/login.php


Note - you won't be able to reach this private IP from any node outside this computer. (In case you need ,you can use Ngnix for that)

Ответ 4

You have to connect your client socket to the remote ServerSocket. Instead of

Socket clientSocket = new Socket("localhost", 5000);

do

Socket clientSocket = new Socket(serverName, 5000);

The client must connect to serverName which should match the name or IP of the box on which your ServerSocket was instantiated (the name must be reachable from the client machine). BTW: It's not the name that is important, it's all about IP addresses...

2023-12-11 07:28 java