java - IOException java.net.ConnectException : failed to connect to/127. 0.0.1(端口 5000):连接失败:ECONNREFUSED(连接被拒绝)

标签 java android sockets

尝试根据本教程进行android socket编程 http://examples.javacodegeeks.com/android/core/socket-core/android-socket-example/

我关闭了防火墙并禁用了防病毒软件。如果我将我的服务器地址设置为 127.0.0.1,我会得到标题中的错误。如果我将它作为我的本地 IP 地址,它就位于将要创建的套接字上。我已经尝试过不使用和使用端口转发并将其设置为相同的端口。

客户端

package com.bennatpjose.androidsocketclient;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
    private Socket socket;
    private TextView text;
    private static final int SERVERPORT = 5000;
    private static final String SERVER_IP = "10.52.7.179";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    text = (TextView) findViewById(R.id.textView1);
    new Thread(new ClientThread()).start();
    text.setText(text.getText().toString()+"Client Thread should be fired");

}

public void onClick(View view) {
    try {

        EditText et = (EditText) findViewById(R.id.EditText01);
        String str = et.getText().toString();
        text.setText(text.getText().toString()+"\n"+"Click Event "+str);
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream())),
                true);
        text.setText(text.getText().toString()+"\n"+"Next is out.println("+str+")");
        out.println(str);
        text.setText(text.getText().toString()+"\n"+"out.println("+str+")");
    } catch (UnknownHostException e) {
        text.setText(text.getText().toString()+"\nPrint Writer UnknownHostException "+e.toString());
    } catch (IOException e) {
        text.setText(text.getText().toString()+"\nPrint Writer IOException "+e.toString());
    } catch (Exception e) {
        text.setText(text.getText().toString()+"\nPrint Writer Exception "+e.toString());
    }
}

class ClientThread implements Runnable {

    @Override
    public void run() {
        text.setText(text.getText().toString()+"\nInside client thread run method ");
        try {
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
//If I set address to my local ip it just sits here and doesn't show socket created.


text.setText(text.getText().toString()+"\n"+serverAddr +" Socket going to be Created");
                socket = new Socket(serverAddr, SERVERPORT);
                text.setText(text.getText().toString()+"\n"+socket.toString() +"Socket Created");
            } catch (UnknownHostException e1) {
                text.setText(text.getText().toString()+"\nClient Thread UnknownHostException "+e1.toString());
            } catch (IOException e1) {
                text.setText(text.getText().toString()+"\nClient Thread IOException "+e1.toString());
            }catch (Exception e1) {
                text.setText(text.getText().toString()+"\nClient Thread Exception "+e1.toString());
            }
    }

}

服务器

package com.bennatpjose.androidsocketserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;

public class MainActivity extends Activity {

    private ServerSocket serverSocket;

    Handler updateConversationHandler;

    Thread serverThread = null;

    private TextView text;

    public static final int SERVERPORT = 6000;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        text = (TextView) findViewById(R.id.text2);
        text.setText(text.getText().toString()+"onCreate method started");
        updateConversationHandler = new Handler();

        this.serverThread = new Thread(new ServerThread());
        this.serverThread.start();
        text.setText(text.getText().toString()+"\n"+"serverThread started");
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {

        serverSocket.close();
        text.setText("!!Socket Stopped!!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class ServerThread implements Runnable {

        public void run() {
            Socket socket = null;
            try {
                serverSocket = new ServerSocket(SERVERPORT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            while (!Thread.currentThread().isInterrupted()) {

                try {

                    socket = serverSocket.accept();
                    text.setText(text.getText().toString()+socket+"\n");

                    CommunicationThread commThread = new CommunicationThread(socket);
                    new Thread(commThread).start();

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

    class CommunicationThread implements Runnable {

        private Socket clientSocket;

        private BufferedReader input;

        public CommunicationThread(Socket clientSocket) {

            this.clientSocket = clientSocket;

            try {

                this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));

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

        public void run() {

            while (!Thread.currentThread().isInterrupted()) {

                try {

                    String read = input.readLine();

                    updateConversationHandler.post(new updateUIThread(read));

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

    }

    class updateUIThread implements Runnable {
        private String msg;

        public updateUIThread(String str) {
            this.msg = str;
        }

        @Override
        public void run() {

            text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
        }
    }
}

最佳答案

所以我想通了。我犯的一个错误是用我的本地 ip 替换 SERVER_IP,因为它是一个特殊的环回地址 android 模拟器,我应该把它留在 10.0.2.2。 10.0.2.2 主机环回接口(interface)的特殊别名(即开发机器上的 127.0.0.1)

您还必须先运行服务器,设置端口重定向,然后再运行客户端。

http://developer.android.com/tools/devices/emulator.html 查找模拟器网络部分

关于java - IOException java.net.ConnectException : failed to connect to/127. 0.0.1(端口 5000):连接失败:ECONNREFUSED(连接被拒绝),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28590366/

相关文章:

Android JSONArray 异常

Android 蓝牙套接字未创建

java - SWT 文本输出和换行

java - CTRL+C在jline2中是如何处理的

java - mouseEnter时如何获取JCombobox Item?

java - 如何使用 java sql 查询 Netbeans 忽略数据库中的字段

android - 设置扫描持续时间

android - 是否可以在 Android 中灰显(不仅仅是禁用)MenuItem?

c - OpenSSL 非阻塞套接字 SSL_read() 不可预测

sockets - 如何在UDP套接字中使用select()从客户端到服务器进行读写