package com.example.transport1;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
EditText commandEditText;
LinearLayout outputLayout;
Button runButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
commandEditText = (EditText) findViewById(R.id.command);
outputLayout = (LinearLayout) findViewById(R.id.command_output);
runButton = (Button) findViewById(R.id.run);
runButton.setOnClickListener(this);
udp("127.0.0.1","3");
udpSender();
}
@Override
public void onClick(View view) {
}
private void udp(String ipAddress,String message) {
new Thread(()->{
try {
final int PORT = 1234; // 目標端口號
InetAddress address = InetAddress.getByName(ipAddress);
// 創(chuàng)建UDP Socket
DatagramSocket socket = new DatagramSocket();
byte[] buffer = message.getBytes();
// 創(chuàng)建要發(fā)送的數(shù)據(jù)包
for(int i=1;i<=100;i++) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, PORT);
// 發(fā)送數(shù)據(jù)包
socket.send(packet);
}
// 關閉Socket
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
private void udpSender() {
new Thread(()->{
Log.d("TAG","線程正在執(zhí)行");
try {
final int PORT = 1234; // 目標端口號
// 創(chuàng)建一個 DatagramSocket 對象,并指定監(jiān)聽的端口號
DatagramSocket socket = new DatagramSocket(PORT);
byte[] buffer = new byte[1];
while (true) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length); // 創(chuàng)建一個 DatagramPacket 對象,用于接收數(shù)據(jù)
// 接收數(shù)據(jù)n
socket.receive(packet);//阻塞狀態(tài),等待數(shù)據(jù)包
// 解析接收到的數(shù)據(jù)
String receivedData = new String(packet.getData(), 0, packet.getLength());
runOnUiThread(() -> commandEditText.setText(receivedData));
Log.d("AAA", receivedData);
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
分別在兩個方法中創(chuàng)建兩個線程,一個作為服務器進行監(jiān)聽,一個作為客戶端進行數(shù)據(jù)發(fā)送。文章來源地址http://www.zghlxwxcb.cn/news/detail-723901.html
文章來源:http://www.zghlxwxcb.cn/news/detail-723901.html
到了這里,關于android studio虛擬機中一個程序模擬udp通信的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!