简体   繁体   English

尝试连接到本地主机上的套接字时出现连接拒绝错误

[英]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. 我正在尝试使用PC上的Java服务器以及以Android应用程序作为客户端的简单服务器-客户端应用程序。 They are both connected to the same wi-fi network. 它们都连接到相同的wi-fi网络。 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. 我使用“ localhost”作为服务器的IP,并确保服务器正在运行并在端口60101上等待连接。该端口未被任何其他应用程序使用,并且正在侦听。 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: 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: 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. android应用程序具有Internet和访问网络状态权限,因此我迷惑了为什么它无法连接到服务器。

OK, you have to find your server IP address in order to set a connection from your app to your server. 好的,您必须找到您的服务器IP地址才能设置从您的应用程序到服务器的连接。 "localhost" is the loopback ip address 127.0.0.1. “本地主机”是回送IP地址127.0.0.1。 In your MainActivity serverAddress must be the IP address of the server. 在MainActivity中,serverAddress必须是服务器的IP地址。 Ex 192.168.0.20 例如192.168.0.20

let's find your local IP address. 让我们找到您的本地IP地址。 Here are the instructions for Windows 这是Windows的说明

Click on the Start menu and type cmd. 单击开始菜单上,然后键入cmd。 When you see the cmd applications in Start menu panel, click it or just press enter. 当您在“开始”菜单面板中看到cmd应用程序时,单击它或仅按Enter键。 A command line window will open. 命令行窗口将打开。 Type ipconfig and press enter. 输入ipconfig并按Enter。 You'll see a bunch of information, but the line you want to look for is "IPv4 Address." 您会看到很多信息,但是您要查找的行是“ IPv4地址”。 The number across from that text is your local IP address. 该文本后面的数字是您的本地IP地址。

Here's how to do the same thing on a Mac: 在Mac上执行以下操作的方法如下:

Open System Preferences (via the Apple menu at the top lefthand corner of your screen). 打开系统偏好设置(通过屏幕左上角的Apple菜单)。 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. 您应该在左侧看到一些带有Wi-Fi,以太网,蓝牙等标签的选项。带有绿点的选项已分配IP地址。 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." 应该有一个句子,上面写着“ Wi-Fi已连接到Chocolate,并且IP地址为192.168.1.102”。 The number at the end of that sentence is your local IP address. 该句子末尾的数字是您的本地IP地址。

You are try to connect server from client with 'localhost' url. 您尝试使用“ localhost” URL从客户端连接服务器。 if there are running on separate machine, write server local ip address instead of 'localhost' 如果在单独的计算机上运行,​​则写入服务器本地IP地址,而不是“ 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";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试连接到套接字时出现NumberFormatException(Throwable)错误 - NumberFormatException(Throwable) error when attempting to connect to a socket 错误:连接到套接字服务器时连接被拒绝 - ERROR: Connection refused when connecting to socket server 连接被拒绝:connect,java socket - Connection refused: connect, java socket 连接被拒绝:连接错误 - Connection refused: connect error 套接字连接异常说连接被拒绝 - Socket connect exception saying connection refused RabbitMq错误-连接被拒绝:连接 - RabbitMq error -Connection refused: connect Elasticsearch 连接时连接被拒绝 - Elasticsearch Connection refused when connect HttpHostConnectException:连接到 localhost:2375 [localhost/127.0.0.1] 失败:连接被拒绝 - HttpHostConnectException: Connect to localhost:2375 [localhost/127.0.0.1] failed: Connection refused TestRestTemplate HttpHostConnectException:连接到本地主机:8082 [localhost/127.0.0.1] 失败:连接被拒绝 - TestRestTemplate HttpHostConnectException: Connect to localhost:8082 [localhost/127.0.0.1] failed: Connection refused Java应用程序无法与本地主机上的MySQL中的特定数据库连接,出现连接拒绝错误 - java application not connect with a specific database in mysql on localhost,connection refused error comes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM