java.net.ConnectException:onnect失败:ECONNREFUSED(拒绝连接)

时间:2016-04-13 14:26:46

标签: android networking android-asynctask

我是这个领域的初学者。我正在尝试制作两个Android设备的连接。 对于任何端口,它显示相同的错误。对于这个tcp连接我应该使用哪个端口?

公共类Main2Activity扩展了AppCompatActivity {

private ListView mList;
private ArrayList<String> arrayList;
private MyCustomAdapter mAdapter;
private TCPClient mTcpClient;
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    Intent myIntent = getIntent();
    String Ip = myIntent.getStringExtra("Ip");
    System.out.println("IP -- " + Ip);
    getSupportActionBar().setTitle(Ip);
    arrayList = new ArrayList<String>();




    final EditText editText = (EditText) findViewById(R.id.editText);
    Button send = (Button)findViewById(R.id.send_button);

    //relate the listView from java to the one created in xml
    mList = (ListView)findViewById(R.id.list);
    mAdapter = new MyCustomAdapter(this, arrayList);
    mList.setAdapter(mAdapter);

    // connect to the server
    new connectTask().execute("");

    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String message = editText.getText().toString();

            //add the text in the arrayList
            if(message.matches("")) {
                Toast.makeText(getApplicationContext(),"You have not entered anything",Toast.LENGTH_LONG).show();
                return;
            }
                arrayList.add("c: " + message);

            //sends the message to the server
            if (mTcpClient != null) {
                mTcpClient.sendMessage(message);
            }
            //refresh the list
            mAdapter.notifyDataSetChanged();
            editText.setText("");




        }
    });

    }

public class connectTask extends AsyncTask<String,String,TCPClient> {

    @Override
    protected TCPClient doInBackground(String... message) {

        //we create a TCPClient object and
        mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
            @Override
            //here the messageReceived method is implemented
            public void messageReceived(String message) {
                //this method calls the onProgressUpdate
                publishProgress(message);
            }
        });
        mTcpClient.run();

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);

        //in the arrayList we add the messaged received from server
        arrayList.add(values[0]);
        // notify the adapter that the data set has changed. This means that new message received
        // from server was added to the list
        mAdapter.notifyDataSetChanged();
    }
}

}

公共类TCPClient {

public static final String SERVER_IP = "192.168.233.101"; //your computer IP address
public static final int SERVER_PORT = 64000;
// message to send to the server
private String mServerMessage;
// sends message received notifications
private OnMessageReceived mMessageListener = null;
// while this is true, the server will continue running
private boolean mRun = false;
// used to send messages
private PrintWriter mBufferOut;
// used to read messages from the server
private BufferedReader mBufferIn;

/**
 * Constructor of the class. OnMessagedReceived listens for the messages received from server
 */
public TCPClient(OnMessageReceived listener) {
    mMessageListener = listener;
}

/**
 * Sends the message entered by client to the server
 *
 * @param message text entered by client
 */
public void sendMessage(String message) {
    if (mBufferOut != null && !mBufferOut.checkError()) {
        mBufferOut.println(message);
        mBufferOut.flush();
    }
}

/**
 * Close the connection and release the members
 */
public void stopClient() {
    Log.i("Debug", "stopClient");

    // send mesage that we are closing the connection
    //sendMessage(Constants.CLOSED_CONNECTION + "Kazy");

    mRun = false;

    if (mBufferOut != null) {
        mBufferOut.flush();
        mBufferOut.close();
    }

    mMessageListener = null;
    mBufferIn = null;
    mBufferOut = null;
    mServerMessage = null;
}

public void run() {

    mRun = true;

    try {
        //here you must put your computer's IP address.
        InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

        Log.e("TCP Client", "C: Connecting...");

        //create a socket to make the connection with the server
        Socket socket = new Socket(serverAddr, SERVER_PORT);

        try {
            Log.i("Debug", "inside try catch");
            //sends the message to the server
            mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

            //receives the message which the server sends back
            mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            // send login name
            //sendMessage(Constants.LOGIN_NAME + PreferencesManager.getInstance().getUserName());
            //sendMessage("Hi");
            //in this while the client listens for the messages sent by the server
            while (mRun) {
                mServerMessage = mBufferIn.readLine();
                if (mServerMessage != null && mMessageListener != null) {
                    //call the method messageReceived from MyActivity class
                    mMessageListener.messageReceived(mServerMessage);
                }

            }
            Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");

        } catch (Exception e) {

            Log.e("TCP", "S: Error", e);

        } finally {
            //the socket must be closed. It is not possible to reconnect to this socket
            // after it is closed, which means a new socket instance has to be created.
            socket.close();
        }

    } catch (Exception e) {

        Log.e("TCP", "C: Error", e);

    }

}

//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
    public void messageReceived(String message);
}

}

错误日志:

    04-13 19:43:34.125 16709-16766/abc.gl E/TCP Client: C: Connecting...
04-13 19:43:34.145 16709-16766/abc.gl E/TCP: C: Error
                                             java.net.ConnectException: failed to connect to /192.168.233.101 (port 64000): connect failed: ECONNREFUSED (Connection refused)
                                                 at libcore.io.IoBridge.connect(IoBridge.java:114)
                                                 at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
                                                 at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
                                                 at java.net.Socket.startupSocket(Socket.java:596)
                                                 at java.net.Socket.<init>(Socket.java:225)
                                                 at abc.gl.TCPClient.run(TCPClient.java:82)
                                                 at abc.gl.Main2Activity$connectTask.doInBackground(Main2Activity.java:94)
                                                 at abc.gl.Main2Activity$connectTask.doInBackground(Main2Activity.java:80)
                                                 at android.os.AsyncTask$2.call(AsyncTask.java:287)
                                                 at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
                                                 at java.util.concurrent.FutureTask.run(FutureTask.java:137)
                                                 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                                                 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
                                                 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
                                                 at java.lang.Thread.run(Thread.java:864)
                                              Caused by: libcore.io.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
                                                 at libcore.io.Posix.connect(Native Method)
                                                 at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
                                                 at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
                                                 at libcore.io.IoBridge.connect(IoBridge.java:112)
                                                 at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 
                                                 at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) 
                                                 at java.net.Socket.startupSocket(Socket.java:596) 
                                                 at java.net.Socket.<init>(Socket.java:225) 
                                                 at abc.gl.TCPClient.run(TCPClient.java:82) 
                                                 at abc.gl.Main2Activity$connectTask.doInBackground(Main2Activity.java:94) 
                                                 at abc.gl.Main2Activity$connectTask.doInBackground(Main2Activity.java:80) 
                                                 at android.os.AsyncTask$2.call(AsyncTask.java:287) 
                                                 at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 
                                                 at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
                                                 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
                                                 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
                                                 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
                                                 at java.lang.Thread.run(Thread.java:864) 
04-13 19:43:34.165 16709-16709/abc.gl E/copybit: Error opening frame buffer errno=13 (Permission denied)    

0 个答案:

没有答案