實現PC端與手機端的UDP通訊
阿新 • • 發佈:2019-01-30
網上的資料很多,也很雜.所以自已參考了網上的程式碼實現了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);
//new Thread(new TcpReceive()).start();
Open();
address = getLocalIPAddress();
if (address != null) {
IPAddress.setText(address);
} else {
IPAddress.setText("Can not get IP address");
return;
}
startButton.setOnClickListener(listener);
stopButton.setOnClickListener(listener);
}
private View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
label.setText("");
if (v == startButton) {
start = true;
new BroadCastUdp(IPAddress.getText().toString()).start();
startButton.setEnabled(false);
stopButton.setEnabled(true);
} else if (v == stopButton) {
start = false;
startButton.setEnabled(true);
stopButton.setEnabled(false);
}
}
};
private String getLocalIPAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
public class BroadCastUdp extends Thread {
private String dataString;
// private DatagramSocket udpSocket;
public BroadCastUdp(String dataString) {
this.dataString = dataString;
}
public void run() {
DatagramPacket dataPacket = null;
try {
// udpSocket = new DatagramSocket(DEFAULT_PORT);
dataPacket = new DatagramPacket(buffer, MAX_DATA_PACKET_LENGTH);
byte[] data = dataString.getBytes();
dataPacket.setData(data);
dataPacket.setLength(data.length);
dataPacket.setPort(DEFAULT_PORT);
InetAddress broadcastAddr;
// broadcastAddr = InetAddress.getByName("255.255.255.255");
//這裡寫目的IP地址
broadcastAddr = InetAddress.getByName("10.10.0.18");
dataPacket.setAddress(broadcastAddr);
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
}
// while( start ){
try {
// udpSocket.send(dataPacket);
if (msocketClient!=null){
msocketClient.send(dataPacket);
}
sleep(10);
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
}
// }
// udpSocket.close();
}
}
public void Open() {
try {
msocketClient = new DatagramSocket(43708);
} catch (Exception e) {
e.printStackTrace();
}
if (msocketClient != null) {
new Thread(UdpReceiver).start();
}
}
Runnable UdpReceiver = new Runnable() {
@Override
public void run() {
while (true) {
byte[] Buffer_Receive = new byte[1024];
Packet_Receive = new DatagramPacket(Buffer_Receive, 1024);
if (Packet_Receive != null) {
try {
msocketClient.receive(Packet_Receive);
int length = Packet_Receive.getLength();
if (length > 0) {
final String data = new String(Packet_Receive.getData());
runOnUiThread(new Runnable() {
@Override
public void run() {
label.setText(data);
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
activity.xml的程式碼
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/start"/>
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/stop"/>
<TextView
android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
在這次測試裡我用網路除錯助手當做PC的傳送和接收測試工具
此時我模擬器端的介面如圖下所示