Android-通过TCP / IP接收WiFi数据

时间:2018-06-27 07:27:02

标签: android tcpclient android-wifi tcp-ip

发送命令以接收数据后,我没有从服务器收到消息。 inputstream.read之后的行不执行。

这是用于从服务器获取消息的可运行代码。

public class ReceiveRunnable implements Runnable {
        private Socket sock;
        private InputStream input;

        public ReceiveRunnable(Socket server) {
            sock = server;
            try {
                input = sock.getInputStream();
            } catch (Exception e) {
            }
        }

        @Override
        public void run() {
            Log.d(TAG, "Receiving started");
            while (isConnected()) {
                if (!receiveThreadRunning)
                    receiveThreadRunning = true;

                startTime = System.currentTimeMillis();
                try {
                    byte[] data = new byte[50];
                    //Read the first integer, it defines the length of the data to expect
                    input.read(data, 0, data.length);
                    int length = data[2];
                    String str = new String(data, "UTF-8"); // for UTF-8 encoding
                    mList.OnDataIncoming(str);
                    stopThreads();
                } catch (Exception e) {
                    if (mList != null)
                        mList.OnConnectionerror();
                    Disconnect(); //Gets stuck in a loop if we don't call this on error!
                }
            }
            receiveThreadRunning = false;
            Log.d(TAG, "Receiving stopped");
        }

    }

0 个答案:

没有答案