简体   繁体   中英

Connection Refused Error when attempting to connect to socket on localhost

I'm trying to set up a simple server-client application using a Java server on my PC, and an android application as the client. They are both connected to the same wi-fi network. I'm running into problems trying to get the client to connect to the server socket. I'm using "localhost" as the IP of the server, and have made sure that the server is running and waiting for a connection on port 60101. The port is not in use by any other applications, and is listening. The client is throwing the connection refused error when I attempt to connect on this line:

connection = new Socket(serverAddress,serverPort);// ("localhost", 60101)

Here is my server code:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {

    private static final int portNumber = 60101;

    public static void main(String[] args) {

        ServerSocket serverSocket = null;

        try {
            //starting server
            System.out.println("Server starting at port number: "+portNumber);
            serverSocket = new ServerSocket(portNumber);

            //client connecting
            System.out.println("Waiting for clients to connect");
            Socket socket = serverSocket.accept();
            System.out.println("Client has connected.");

            //Send message to the client
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write("this is a message from the server");
            bw.newLine();
            bw.flush();

            //Receive message from client
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String data;
            while((data = br.readLine()) != null ){
                System.out.println("Message from the client: " + data);

            }
            System.out.println("Server has ended");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Android MainActivity.java:

package johnedchristensen.androidclienttestapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView showMessageText;
    Button buttonConnect;
    String serverAddress = "localhost";
    int portNumber = 60101;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        showMessageText = (TextView) findViewById(R.id.textView);
        buttonConnect = (Button) findViewById(R.id.button);

        buttonConnect.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Client myClient = new Client(serverAddress, portNumber, showMessageText);
                myClient.execute();
            }
        });
    }
}

Android Client.java:

package johnedchristensen.androidclienttestapplication;

import android.os.AsyncTask;
import android.widget.TextView;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;



public class Client extends AsyncTask<Void,Void,Void>{
    private String serverAddress;
    private int serverPort;
    private TextView messageDisplay;
    private Socket connection;
    private String statusMessage = "";

    Client(String address, int port, TextView message){
        serverAddress = address;
        serverPort = port;
        this.messageDisplay = message;

    }

    @Override
    protected Void doInBackground(Void... params) {


        try{
            //connection
            statusMessage += "Attempting to connect... \n";
            connection = new Socket(serverAddress,serverPort);
            statusMessage += "Connected to: " + connection.getInetAddress().getHostName();

        }catch(EOFException eofException){
            statusMessage +="\n Error Connecting";
        }catch(IOException ioException){
            statusMessage +="\n Error Connecting";
            ioException.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        messageDisplay.setText(statusMessage);
        super.onPostExecute(result);
    }

}

And the Connection refused Error:

 W/System.err: java.net.ConnectException: Connection refused
 W/System.err:     at java.net.PlainSocketImpl.socketConnect(Native Method)
 W/System.err:     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:334)
 W/System.err:     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
 W/System.err:     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
 W/System.err:     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
 W/System.err:     at java.net.Socket.connect(Socket.java:586)
 W/System.err:     at java.net.Socket.connect(Socket.java:535)
 W/System.err:     at java.net.Socket.<init>(Socket.java:427)
 W/System.err:     at java.net.Socket.<init>(Socket.java:210)
 W/System.err:     at johnedchristensen.androidclienttestapplication.Client.doInBackground(Client.java:43)
 W/System.err:     at johnedchristensen.androidclienttestapplication.Client.doInBackground(Client.java:19)
 W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:304)
 W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
 W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
 W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
 W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
 W/System.err:     at java.lang.Thread.run(Thread.java:761)

The android application has internet and access network state permissions, so I'm at a loss for why it won't connect to the server.

OK, you have to find your server IP address in order to set a connection from your app to your server. "localhost" is the loopback ip address 127.0.0.1. In your MainActivity serverAddress must be the IP address of the server. Ex 192.168.0.20

let's find your local IP address. Here are the instructions for Windows

Click on the Start menu and type cmd. When you see the cmd applications in Start menu panel, click it or just press enter. A command line window will open. Type ipconfig and press enter. You'll see a bunch of information, but the line you want to look for is "IPv4 Address." The number across from that text is your local IP address.

Here's how to do the same thing on a Mac:

Open System Preferences (via the Apple menu at the top lefthand corner of your screen). When System Preferences opens, click on the icon labeled Network. You should see a few options on the left with labels like Wi-Fi, Ethernet, Bluetooth, etc. The ones with green dots have IP addresses assigned to them. Click the one on top (if it isn't already selected) and look to the right. There should be a sentence that reads something like "Wi-Fi is connected to Chocolate and has the IP address 192.168.1.102." The number at the end of that sentence is your local IP address.

You are try to connect server from client with 'localhost' url. if there are running on separate machine, write server local ip address instead of 'localhost'

if the client runs in emulator, maybe the emulator and the server is not in the same network.

String serverAddress = "192.168.x.xx";

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