我的TCP客户端无法连接到服务器。获取“连接失败:ETIMEDOUT”

时间:2017-04-08 10:35:40

标签: java android tcp tcpclient wifi-direct

我通过WiFi直接将手机连接到传感器。我应该连接到端口5001以获取传感器数据。我一直在设置TCP客户端时遇到问题,因此我可以打开端口并检索数据。我发现这篇帖子Really simple TCP client我复制粘贴了代码。

要测试我的代码,我使用应用程序“Simple Socket Tester”,我在另一部手机上启动IP地址为192.168.1.52,端口5001的服务器。我通过WiFi直接连接手机,成功连接后ConnectTask代码应该运行。但我得到“java.net.ConnectException:无法连接到/192.168.1.52(端口5001):连接失败:ETIMEDOUT(连接超时)”。为什么会这样?我做错了什么?。

修改

我设法现在连接到服务器。但现在我无法看到我从服务器发送的消息。

以下是我正在做的详细演练,

  1. 我在另一部手机上的“Simple Socket Tester”上启动服务器。
  2. 我直接从我的应用程序使用WiFi连接两部手机。连接完成后,“ConnectTask”运行。
  3. 我回到另一部手机上的“Simple Socket Tester”,看到客户端已连接到服务器。
    1. 我从服务器发送消息,但无法在客户端看到该消息。如何显示服务器发送的消息?
  4. 我的TCP客户端代码:

    public class TCPClient {
    public static final String SERVER_IP = "192.168.1.52"; //your computer IP address
    public static final int SERVER_PORT = 5001;
    // 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);
    
        }
    
    }
    

    我的ConnectTask

    public class ConnectTask extends AsyncTask<String, String, TCPClient> {
    
    @Override
    protected TCPClient doInBackground(String... message) {
    
        //we create a TCPClient object
        TCPClient 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);
        //response received from server
        Log.d("test", "response " + values[0]);
        //process server response here....
    
    }
    }
    

    我的WiFi直接活动中启动ConnectTask的部分

    public class WiFiDirectActivity extends Activity implements WifiP2pManager.ChannelListener, DeviceListFragment.DeviceActionListener {
    ...
    
        @Override
    public void connect(WifiP2pConfig config) {
        config.groupOwnerIntent = 0;
        manager.connect(channel, config, new WifiP2pManager.ActionListener()
        {
    
            @Override
            public void onSuccess() {
                // WiFiDirectBroadcastReceiver will notify us. Ignore for now.
                new ConnectTask().execute("");
                //sends the message to the server
                if (mTCPClient != null) {
                    mTCPClient.sendMessage("testing");
                }
    
            }
    
            @Override
            public void onFailure(int reason) {
                Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",
                        Toast.LENGTH_SHORT).show();
            }
        });
    

0 个答案:

没有答案