问题描述
我想在没有互联网的情况下使用wifi在两个或多个设备上聊天。我正在使用套接字从第一台Android手机向第二台手机发送消息。我遇到了一个问题,即在第二个手机上收到了一些按摩,而跳过了一些按摩,而没有收到。我尝试了Multicastsoket和Datagramsoket,但是跳过了短信。以下是我的发送方和接收方代码。
**- Sender side**
public static void sender(final String ipAddress,final String message) {
// Creates the thread for capturing and transmitting audio
/* AsyncTaskExample asyncTask = new AsyncTaskExample();
asyncTask.execute(message);*/
Thread replyThread = new Thread(new Runnable() {
@Override
public void run() {
try {
InetAddress address = InetAddress.getByName(ipAddress);
byte[] data = message.getBytes();
DatagramSocket socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(data,data.length,address,broADCAST_PORT);
socket.setReuseAddress(true);
socket.send(packet);
Log.i(LOG_TAG,"Sent message( " + message + " ) to " + ipAddress);
socket.disconnect();
socket.close();
} catch (UnkNownHostException e) {
Log.e(LOG_TAG,"Failure. UnkNownHostException in sendMessage: " + ipAddress);
} catch (SocketException e) {
Log.e(LOG_TAG,"Failure. SocketException in sendMessage: " + e);
} catch (IOException e) {
Log.e(LOG_TAG,"Failure. IOException in sendMessage: " + e);
}
}
});
replyThread.start();
}
**- Receiver side**
public void receiver() {
// Creates the thread for receiving massage
Thread receiveThread = new Thread(new Runnable() {
@Override
public void run() {
try {
DatagramSocket socket = new DatagramSocket(broADCAST_PORT);
// InetAddress group = InetAddress.getByName(myIPAddress);
//socket.setSoTimeout(1000);
byte[] buffer = new byte[BUF_SIZE];
DatagramPacket packet = new DatagramPacket(buffer,BUF_SIZE);
while (LISTEN) {
// Listen for incoming call requests
try {
Log.i(LOG_TAG,"Listening for incoming message");
/* Arrays.fill(buffer,(byte)0);*/
socket.receive(packet);
String data = new String(buffer,packet.getLength());
Log.i("SocketMSG","Packet received from " + packet.getAddress() + " with contents: " + data);
String action = data.substring(0,4);
//Toast.makeText(context,"Packet received from",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
socket.disconnect();
socket.close();
} catch (SocketException e) {
e.printstacktrace();
} catch (IOException e) {
e.printstacktrace();
}
});
receiveThread.start();
}
解决方法
您可以在UDP之上实现类似TCP的行为,例如,请参见此存储库:https://github.com/jin-zhe/reliable-UDP/blob/master/Sender.java