多个读写套接字

时间:2019-01-10 06:54:49

标签: android multithreading sockets tcp

我需要一个应用程序来连接Wifi板。通过单击每个人,我有四个片段,我必须先写入arraybyte或一个字节,然后读取arrayByte。 第一次,我无需编写即可读取arrayBte,它是完美的工作,但是通过单击其他片段,我总是得到null。 这是我的代码:

public class CommsThread extends Thread {
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;

public CommsThread() {
    try {
        socket = new Socket(Const.ip, Const.port);
    } catch (IOException e) {
        e.printStackTrace();
    }
    InputStream tmpIn = null;
    OutputStream tmpOut = null;
    try {
        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();

    } catch (IOException e) {
        Log.d("SocketChat", e.getLocalizedMessage());
    }
    inputStream = tmpIn;
    outputStream = tmpOut;
}

public void run() {
    while (true) {
        try {
            byte[] data = new byte[1];
            inputStream.read(data);
            readData.add(data[0]);
        } catch (IOException e) {
        }
    }
}

 public void write(ArrayList<Byte> bytes) {
        ArrayList list = new ArrayList();
        list.add((byte)0xFE);
    for (byte b: bytes)
    {
        if(b >= 0xFD)
        {
            list.add((byte)0xFD);
            list.add((byte)(b - 0xFD));
        }
        else
            list.add(b);
    }
    list.add((byte)0xFF);
    byte[] listBytes = new byte[list.size()];
    for (int i = 0; i < list.size(); i++) {
        listBytes[i] = (byte)list.get(i);
    }
    try {
        outputStream.write(listBytes);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

我在asynckTask类中使用了以下代码:

Const.commsThread = new CommsThread();
                Const.commsThread.start();

通过单击一个片段,我调用写功能:

//for example
     sendToServer("5");

 public static class WriteToServerTask extends AsyncTask<byte[], Void, Void> {
    protected Void doInBackground(byte[]... data) {
        ArrayList list = new ArrayList();
        list.add((byte)0x05);

        Const.commsThread.write(list);
        return null;
    }
}

public static void sendToServer(String message) {
    byte[] theByteArray = message.getBytes();
    new WriteToServerTask().execute(theByteArray);
}

我没有收到错误,但是执行写功能时它永远不会退出。 预先感谢。

2 个答案:

答案 0 :(得分:0)

我得到了答案:

起初:

new CreateCommThreadTask().execute();

CreateCommThreadTask:

   private class CreateCommThreadTask extends AsyncTask<Void, Integer, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                // ---create a socket---
                //  Const.socket = new Socket(Const.ip, Const.port);
                Socket socket = new Socket("192.168.4.1", 8888);
                Const.commsThread = new CommsThread(socket);
                Const.commsThread.start();

            } catch (UnknownHostException e) {
                Log.d("Sockets", e.getLocalizedMessage());
            } catch (IOException e) {
                Log.d("Sockets", e.getLocalizedMessage());
            }
            return null;
        }
    }

CommsThread:

public class CommsThread extends Thread {
    private Socket socket;
    private InputStream inputStream;
    private OutputStream outputStream;
    public static ArrayList<Byte> readData = new ArrayList<Byte>();

    public CommsThread(Socket sock) {
        socket = sock;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();

        } catch (IOException e) {
            Log.d("SocketChat", e.getLocalizedMessage());
        }
        inputStream = tmpIn;
        outputStream = tmpOut;
    }

    public void run() {
        while (true) {
            try {
                byte[] data = new byte[1];
                inputStream.read(data);
                readData.add(data[0]);

            } catch (IOException e) {

            }
        }

    }

    // send data to the remote device---
    public void write(ArrayList<Byte> bytes) {
        ArrayList list = new ArrayList();
        list.add((byte) 0xFE);
        for (byte b : bytes) {
            if (b >= 0xFD) {
                list.add((byte) 0xFD);
                list.add((byte) (b - 0xFD));
            } else
                list.add(b);
        }
        list.add((byte) 0xFF);
        byte[] listBytes = new byte[list.size()];
        for (int i = 0; i < list.size(); i++) {
            listBytes[i] = (byte) list.get(i);
        }
        try {
            outputStream.write(listBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // ---call this from the main activity to
    // shutdown the connection---
    public void cancel() {
        try {
            socket.close();
        } catch (IOException e) {
        }
    }
}

写:

new WriteToServerTask().execute(theByteArray);

WriteToServerTask:

public static class WriteToServerTask extends AsyncTask<byte[], Void, Void> {
        protected Void doInBackground(byte[]... data) {
            ArrayList list = new ArrayList();
            list.add((byte) 0x05);
            Const.commsThread.write(list);
            return null;
        }
    }

它运行完美。

答案 1 :(得分:-1)

MSQATVHM很可能是response2,因为null返回-1。例如,如果套接字已被对等方(docs)关闭,就是这种情况。

您应该为-1情况添加一些其他处理。还可以考虑添加一些日志记录,以帮助您了解程序中正在发生的事情。

inputStream.read(Const.data2)将在您调用run()之后不久异步执行。