我使用以下代码将UDP数据包发送到服务器。此代码在PC上工作正常。但是当涉及到Android设备时...方法test()
无法打印任何内容...我在做什么错?请指教。
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.os.Build;
@SuppressLint("NewApi") public class MainActivity extends ActionBarActivity {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
@Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
test();
}
});
}
void test()
{
// Find the server using UDP broadcast
try {
//Open a random port to send the package
DatagramSocket c = new DatagramSocket();
c.setBroadcast(true);
byte[] sendData = "DISCOVER_FUIFSERVER_REQUEST".getBytes();
//Try the 255.255.255.255 first
try {
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 8888);
c.send(sendPacket);
// Log.d("MyApp",getClass().getName() + ">>> Request packet sent to: 255.255.255.255 (DEFAULT)");
} catch (Exception e) {
// Log.d("MyApp",e.getMessage());
}
// Broadcast the message over all the network interfaces
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.isLoopback() || !networkInterface.isUp()) {
continue; // Don't want to broadcast to the loopback interface
}
for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
InetAddress broadcast = interfaceAddress.getBroadcast();
if (broadcast == null) {
continue;
}
// Send the broadcast package!
try {
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888);
c.send(sendPacket);
} catch (Exception e) {
//Log.d("MyApp",e.getMessage());
}
// Log.d("MyApp",getClass().getName() + ">>> Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName());
}
}
// Log.d("MyApp",getClass().getName() + ">>> Done looping over all network interfaces. Now waiting for a reply!");
//Wait for a response
byte[] recvBuf = new byte[15000];
DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
c.receive(receivePacket);
//We have a response
//Check if the message is correct
String message = new String(receivePacket.getData()).trim();
if (message.equals("DISCOVER_FUIFSERVER_RESPONSE")) {
//DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller)
// Controller_Base.setServerIp(receivePacket.getAddress());
}
//Close the port!
c.close();
} catch (IOException ex) {
// Log.d("MyApp",ex.getMessage());
}
}
}
更新:
错误:
06-03 14:50:35.038: E/AndroidRuntime(31361): FATAL EXCEPTION: main
06-03 14:50:35.038: E/AndroidRuntime(31361): Process: com.example.project, PID: 31361
06-03 14:50:35.038: E/AndroidRuntime(31361): java.lang.NullPointerException: println needs a message
06-03 14:50:35.038: E/AndroidRuntime(31361): at android.util.Log.println_native(Native Method)
06-03 14:50:35.038: E/AndroidRuntime(31361): at android.util.Log.d(Log.java:139)
06-03 14:50:35.038: E/AndroidRuntime(31361): at com.example.project.MainActivity.test(MainActivity.java:64)
06-03 14:50:35.038: E/AndroidRuntime(31361): at com.example.project.MainActivity$1.onClick(MainActivity.java:39)
06-03 14:50:35.038: E/AndroidRuntime(31361): at android.view.View.performClick(View.java:4756)
06-03 14:50:35.038: E/AndroidRuntime(31361): at android.view.View$PerformClick.run(View.java:19761)
06-03 14:50:35.038: E/AndroidRuntime(31361): at android.os.Handler.handleCallback(Handler.java:739)
06-03 14:50:35.038: E/AndroidRuntime(31361): at android.os.Handler.dispatchMessage(Handler.java:95)
06-03 14:50:35.038: E/AndroidRuntime(31361): at android.os.Looper.loop(Looper.java:135)
06-03 14:50:35.038: E/AndroidRuntime(31361): at android.app.ActivityThread.main(ActivityThread.java:5253)
06-03 14:50:35.038: E/AndroidRuntime(31361): at java.lang.reflect.Method.invoke(Native Method)
06-03 14:50:35.038: E/AndroidRuntime(31361): at java.lang.reflect.Method.invoke(Method.java:372)
06-03 14:50:35.038: E/AndroidRuntime(31361): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
06-03 14:50:35.038: E/AndroidRuntime(31361): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
最佳答案
尝试使用“ Log.d”代替“ System.out.println”
编辑
并在连接前检查字符串的空值。也就是说,对所有Log.d方法执行以下操作:
if ( broadcast! = null && broadcast.getHostAddress() && networkInterface! =null&&networkInterface.getDisplayName()!=null)
{
Log.d("MyApp",getClass().getName() + ">>> Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName());
}
编辑
用
test()
包装Thread
函数:new Thread(new Runnable() {
@Override
public void run() {
test();
}
}).start();
关于java - UDP数据包发现不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37609692/