我有運行與發送和接收TCP連接的工作代碼。 這裏是我的CreateCommThreadTask
,WriteToServer
和CloseSocketTask
類:Android的 - 轉換TCP客戶端UDP客戶
private class CreateCommThreadTask extends AsyncTask
<Void, Integer, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
//---create a socket---
serverAddress =
InetAddress.getByName("192.168.4.1");
socket = new Socket(serverAddress, 8080);
commsThread = new CommsThread(socket);
commsThread.start();
} catch (UnknownHostException e) {
Log.d("Sockets", e.getLocalizedMessage());
} catch (IOException e) {
Log.d("Sockets", e.getLocalizedMessage());
}
return null;
}
}
private class WriteToServerTask extends AsyncTask
<byte[], Void, Void> {
protected Void doInBackground(byte[]...data) {
commsThread.write(data[0]);
return null;
}
}
private class CloseSocketTask extends AsyncTask
<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
socket.close();
} catch (IOException e) {
Log.d("Sockets", e.getLocalizedMessage());
}
return null;
}
}
,並用這個類我讀的輸入數據:
public class CommsThread extends Thread {
private final Socket socket;
private final InputStream inputStream;
private final OutputStream outputStream;
public CommsThread(Socket sock) {
socket = sock;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//---creates the inputstream and outputstream objects
// for reading and writing through the sockets---
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.d("SocketChat", e.getLocalizedMessage());
}
inputStream = tmpIn;
outputStream = tmpOut;
}
public void run() {
//---buffer store for the stream---
byte[] buffer = new byte[1024];
//---bytes returned from read()---
int bytes;
//---keep listening to the InputStream until an
// exception occurs---
while (true) {
try {
//---read from the inputStream---
bytes = inputStream.read(buffer);
//---update the main activity UI---
SocketsActivity.UIupdater.obtainMessage(
0,bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//---call this from the main activity to
// send data to the remote device---
public void write(byte[] bytes) {
try {
outputStream.write(bytes);
} catch (IOException e) { }
}
//---call this from the main activity to
// shutdown the connection---
public void cancel() {
try {
socket.close();
} catch (IOException e) { }
}
}
最後我用用Handler
像這樣我接收到的數據:
static Handler UIupdater = new Handler() {
@Override
public void handleMessage(Message msg) {
int numOfBytesReceived = msg.arg1;
byte[] buffer = (byte[]) msg.obj;
//---convert the entire byte array to string---
//---extract only the actual string received---
if(numOfBytesReceived>0)
{
strReceived = new String(buffer);
strReceived = strReceived.substring(0, numOfBytesReceived);
}
//---display the text received on the TextVie*---
}
};
這些代碼在TCP連接的罰款。我的問題是需要進行哪些更改才能將它們轉換爲UDP客戶端? 我想在AsyncTask
中實現UDP,與我寫的TCP代碼相同。
我如何使用它完全像我寫的代碼TCP? (的AsyncTask) –