Programing

java.net.ConnectException : 연결 거부

crosscheck 2020. 5. 27. 21:36
반응형

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);
                }
            }
        }
    }
}

이 예외는 연결하려는 IP / 포트에서 서비스 수신 대기가 없음을 의미합니다.

  • 잘못된 IP / 호스트 또는 포트에 연결하려고합니다.
  • 서버를 시작하지 않았습니다.
  • 서버가 연결을 수신하지 않습니다.
  • Windows 서버에서 청취 백 로그 큐가 가득 찼습니다.

나는 확인할 것이다 :

  • 연결하려는 호스트 이름 및 포트
  • 서버 측이 올바르게 청취를 시작했습니다.
  • 연결을 차단하는 방화벽이 없습니다

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.


I had the same problem, but running the Server before running the Client fixed it.


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...


I had the same problem with Mqtt broker called vernemq.but solved it by adding the following.

  1. $ sudo vmq-admin listener show

to show the list o allowed ips and ports for vernemq

  1. $ sudo vmq-admin listener start port=1885 -a 0.0.0.0 --mountpoint /appname --nr_of_acceptors=10 --max_connections=20000

to add any ip and your new port. now u should be able to connect without any problem.

Hope it solves your problem. enter image description here


Hope my experience may be useful to someone. I faced the problem with the same exception stack trace and I couldn't understand what the issue was. The Database server which I was trying to connect was running and the port was open and was accepting connections.

The issue was with internet connection. The internet connection that I was using was not allowed to connect to the corresponding server. When I changed the connection details, the issue got resolved.


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)


In my case, I gave the socket the name of the server (in my case "raspberrypi"), and instead an IPv4 address made it, or to specify, IPv6 was broken (the name resolved to an IPv6)


In my case, I had to put a check mark near Expose daemon on tcp://localhost:2375 without TLS in docker setting (on the right side of the task bar, right click on docker, select setting)


i got this error because I closed ServerSocket inside a for loop that try to accept number of clients inside it (I did not finished accepting all clints)

so be careful where to close your Socket


I had same problem and the problem was that I was not closing socket object.After using socket.close(); problem solved. This code works for me.

ClientDemo.java

public class ClientDemo {
    public static void main(String[] args) throws UnknownHostException,
            IOException {
        Socket socket = new Socket("127.0.0.1", 55286);
        OutputStreamWriter os = new OutputStreamWriter(socket.getOutputStream());
        os.write("Santosh Karna");
        os.flush();
        socket.close();
    }
}

and ServerDemo.java

public class ServerDemo {
    public static void main(String[] args) throws IOException {
        System.out.println("server is started");
        ServerSocket serverSocket= new ServerSocket(55286);
        System.out.println("server is waiting");
        Socket socket=serverSocket.accept();
        System.out.println("Client connected");
        BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String str=reader.readLine();
        System.out.println("Client data: "+str);
        socket.close();
        serverSocket.close();

    }
}

It could be that there is a previous instance of the client still running and listening on port 5000.


I had the same issue, and it turned out to be due to permission of the catalina.out file not being correct. It was not writable by the tomcat user. Once I fixed the permissions, the issue got resolved. I got to know that it is a permissions issue from the logs in the tomcat8-initd.log file:

/usr/sbin/tomcat8: line 40: /usr/share/tomcat8/logs/catalina.out: Permission denied

참고URL : https://stackoverflow.com/questions/6876266/java-net-connectexception-connection-refused

반응형