在android中接收UDP数据包
我能够在android中执行UDP广播。客户端应发送其IP地址。如果有3到4个客户端在同一网络上运行,我只收到一个客户端的回复。 我想收到所有客户的回复。这是我的广播代码,它甚至可以接收客户发送的数据在android中接收UDP数据包,android,udp,Android,Udp,我能够在android中执行UDP广播。客户端应发送其IP地址。如果有3到4个客户端在同一网络上运行,我只收到一个客户端的回复。 我想收到所有客户的回复。这是我的广播代码,它甚至可以接收客户发送的数据 public class Scan4Activity extends Activity { TextView tv; int i=-1; /** Called when the activity is first created. */ @Override public void onCreate
public class Scan4Activity extends Activity {
TextView tv;
int i=-1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("ggrerrrrrrrggg", "hhaqaaaaaaaaaaahhhhhhh");
setContentView(R.layout.main);
//String[] b=;
try {
Log.i("ggggg", "hhhhhhhhh");
String modifiedSentence="received!!!:)";
main(null);
Toast.makeText(getApplicationContext(), modifiedSentence, Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("FROM SERVER:error");
e.printStackTrace();
}
}
public void main(String args[]) throws Exception
{
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("255.255.255.255");
byte[] sendData = new byte[1024];
String sentence = "hello";//inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 16789);
clientSocket.send(sendPacket);
while(true){
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
Toast.makeText(getApplicationContext(), modifiedSentence, Toast.LENGTH_SHORT).show();
System.out.println("FROM SERVER:" + modifiedSentence);
try{
clientSocket.close();
}
catch(Exception e){
System.err.println("Cannot Close the Socket" );
}
}
}
有谁能帮忙吗 当您进行测试时,您是通过2g/3g网络进行测试,还是通过wifi进行测试,因为如果您使用2g/3g进行测试,您的手机上很可能没有静态ip,而是通过一些“本地”进行测试ip仅在2g/3g网络中有效,一旦udp包离开移动运营商网络并进入互联网,它看起来就像来自运营商ip,因此对所有手机都是一样的。否。我不是在2g/3g网络上测试它,而是在WIFI上测试它。。。我正在使用255.255.255.255进行广播。。