您好我目前正在使用DatagramSockets在Android中创建一个项目,我在编程方面并不是那么好。我正在制作一个注册页面。我的Android设备使用用户名和收据代码等信息连接到电脑。我的电脑可以收到数据。当我的电脑收到数据时,我需要检查收据代码是否有效和未使用。然后,如果它无效,未使用,使用或有效,我会发送给客户端。问题是我的android设备无法接收pc发送的数据。我真的需要你的帮助。目前我正在使用模拟器。我需要专家的帮助。这是我的代码:
Android设备:
public class RegisterAsyncTask extends AsyncTask<String, Integer, String>{
private DatagramSocket socket;
private DatagramPacket p;
private byte[] receiveData = new byte[1024];
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
InetAddress local = InetAddress.getByName("10.0.2.2");
socket = new DatagramSocket();
p = new DatagramPacket(params[0].getBytes(), params[0].length(),local,12345);
socket.send(p);
Log.d ("asd", "Packet sent");
p = new DatagramPacket (receiveData, receiveData.length);
Log.d ("asd", "Receiving packet");
socket.receive(p);
Log.d ("asd", "Packet received");
String message = new String (p.getData(), 0 , p.getLength());
Log.d ("asd", message);
return message;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
PC:
public class HandleAClient {
private DatagramSocket socket;
private DatagramPacket packet;
private int server_port = 12345;
private byte[] receiveData = new byte[1024];
private String receiptCode;
private InetAddress clientAddress;
private String errorMessage;
public HandleAClient (DatagramSocket socket, DatagramPacket packet) {
//Initializes instance variables
this.socket = socket;
this.packet = packet;
}
public void registerClient () {
try {
String message = new String (packet.getData(),0,packet.getLength());
Parser parser = new Parser();
receiptCode = parser.getReceiptCode(message);
System.out.println (receiptCode);
System.out.println ("Message: " + message + " on " + packet.getAddress() + " on port " + server_port);
String cadd = packet.getAddress().toString();
String newcadd = cadd.substring(1, cadd.length());
System.out.println (newcadd);
clientAddress = InetAddress.getByName(newcadd);
if (!ControlVariables.db.checkReceiptCode(receiptCode)) {
errorMessage = "Invalid Code";
System.out.println (errorMessage);
packet = new DatagramPacket(errorMessage.getBytes(), errorMessage.length(),clientAddress,12345);
socket.send(packet);
System.out.println ("error message send" + " to " +newcadd);
}
else {
ReceiptCode rc = new ReceiptCode();
rc = ControlVariables.db.getReceiptCode(receiptCode);
if (rc.getStatus().equals("used")) {
errorMessage = "Used Code";
packet = new DatagramPacket(errorMessage.getBytes(), errorMessage.length(),clientAddress,12345);
socket.send(packet);
}
else {
System.out.println (receiptCode);
System.out.println ("Message: " + message + " on " + packet.getAddress() + " on port " + server_port);
errorMessage = "Successful";
packet = new DatagramPacket(errorMessage.getBytes(), errorMessage.length(),clientAddress,12345);
socket.send(packet);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
由于我无法在您的帖子中添加评论,我会尝试这种方式。
我<{3}} 模拟器无法使用真正的互联网连接。所以我没有意识到你如何将数据发送到PC。
请提供有关未收到数据包的错误或信息的更多信息。