网上的资料很多,也很杂.所以自已参考了网上的代码实现了UDP的简单通信.在实现的过程的遇到了很多的坑.在这要强调一个基础点,当你用网络调试助手发送UDP消息到安卓模拟器的时候,端口号并不是你本机的端口号.模拟器会有一个自已的端口号,本人在这就吃过很大的亏.导致数据一直接收不到.接下来贴上简单的实现代码.
MainActivity
public class MainActivity extends Activity {
private static String LOG_TAG = "WifiBroadcastActivity";
private boolean start = true;
private EditText IPAddress;
private String address;
public static final int DEFAULT_PORT = 43708;
private static final int MAX_DATA_PACKET_LENGTH = 40;
private byte[] buffer = new byte[MAX_DATA_PACKET_LENGTH];
Button startButton;
Button stopButton;
TextView label;
private DatagramSocket msocketClient;
private DatagramPacket Packet_Receive;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IPAddress = (EditText) this.findViewById(R.id.address);
startButton = (Button) this.findViewById(R.id.start);
stopButton = (Button) this.findViewById(R.id.stop);
label = (TextView) this.findViewById(R.id.label);
startButton.setEnabled(true);
stopButton.setEnabled(false);
Open();
address = getLocalIPAddress();
if (address != null) {
IPAddress.setText(address);