Android的 - 转换TCP客户端UDP客户
问题描述:
我有运行与发送和接收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代码相同。
答
要使用UDP,您应该使用DatagramSocket
要发送消息:
DatagramSocket serverSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName(ipAddress);
byte[] sendData = message.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
要收到一条消息:
byte[] receiveData = new byte[15]; //max length 15.
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
DatagramSocket clientSocket = new DatagramSocket(port);
clientSocket.receive(receivePacket);
String receivedMessage = new String(receivePacket.getData()).trim();
答
TCP & UDP之间的主要区别是,TCP是一个连接的套接字,你首先需要建立一个连接然后发送或接收数据包。 与UDP不同,您可以直接将数据包发送到IP +目的地端口,而无需以前的连接,它是一个未连接的套接字。
随着UDP数据包的大小是有限的,建议不要超过512个字节,而不是用TCP还有的没有限制。
使用UDP不能保证数据包会在另一边接收,发送者不会有它是否收到任何确认,而不是在TCP有这样的验证。
如果你需要确保发送在另一侧被接收的字节数,你需要使用TCP和UDP不
而且还知道,其实有些手机公司不分配任何更多的连接公共IP给客户端,他们分配私有IP。在这种情况下,Android设备不能充当服务器,这意味着无法等待接收到的UDP数据包,并且由于其端口无法从WAN访问而无法侦听传入的TCP连接。
我如何使用它完全像我写的代码TCP? (的AsyncTask) –