我正在開發一個使用Wifi/TCP連接與機器人進行通信的應用程序。目前,我正在使用一個單線程來管理使用TcpClient類和我的MainActivity中的「ConnectTask extends AsyncTask」的tcp連接。在AsyncTask中處理程序的使用
到目前爲止,這是我:
TcpClient.java
private OnMessageReceived mMessageListener = null;
private int bufferSize = 5000;
public ByteBuffer bf;
private BufferedInputStream inFromServer;
private BufferedOutputStream outFromClient;
.
.
.
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");
//receives the message which the server sends back
inFromServer = new BufferedInputStream(socket.getInputStream());
outFromClient = new BufferedOutputStream(socket.getOutputStream());
bf = ByteBuffer.allocate(bufferSize);
while (mRun) {
// Log.i("Debug", "inside while mRun");
bf.order(ByteOrder.LITTLE_ENDIAN);
for (int i=0;i<5000;i++) {
int b = inFromServer.read();
if (b == -1) {
break;
}
bf.put((byte) b);
}
if (bf != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
// Log.i("Debug","Message received !");
mMessageListener.messageReceived(bf);
mMessageListener.updateBatteryLvl();
}
bf.position(0);
}
}
.
.
.
這是我在MainActivity ConnectTask:
public class ConnectTask extends AsyncTask<Void, ByteBuffer, TcpClient> {
@Override
protected TcpClient doInBackground(Void... params) {
//we create a TCPClient object and
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
@Override
//here the messageReceived method is implemented
public void messageReceived(ByteBuffer message) throws IOException {
//this method calls the onProgressUpdate
byte[] resultat = new byte[4000];
resultat = message.array();
updateBatteryLvl();
message.clear();
我沒有使用任何TcpClient的處理程序
或connecttask,但我已經看到一些使用它們的Tcp連接教程,我想知道他們爲什麼使用它?我已經測試了與機器人的連接,並且收到它發送的數據非常好。 處理程序是否像信號量一樣使用,如果你有多線程寫在同一個文件中例如?