私は、送受信と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クライアントに変換するために必要な変更です。 私が書いたTCPコードと同じAsyncTask
にUDPを実装したいと思います。
私が書いたTCPコードとまったく同じように使用するにはどうすればよいですか? (AsyncTask) –