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);
// 创建UDP Socket
DatagramSocket socket = new DatagramSocket();
byte[] buffer = message.getBytes();
// 创建要发送的数据包
for(int i=1;i<=100;i++) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, PORT);
// 发送数据包
socket.send(packet);
}
// 关闭Socket
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
private void udpSender() {
new Thread(()->{
Log.d("TAG","线程正在执行");
try {
final int PORT = 1234; // 目标端口号
// 创建一个 DatagramSocket 对象,并指定监听的端口号
DatagramSocket socket = new DatagramSocket(PORT);
byte[] buffer = new byte[1];
while (true) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length); // 创建一个 DatagramPacket 对象,用于接收数据
// 接收数据n
socket.receive(packet);//阻塞状态,等待数据包
// 解析接收到的数据
String receivedData = new String(packet.getData(), 0, packet.getLength());
runOnUiThread(() -> commandEditText.setText(receivedData));
Log.d("AAA", receivedData);
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
分别在两个方法中创建两个线程,一个作为服务器进行监听,一个作为客户端进行数据发送。文章来源地址https://www.toymoban.com/news/detail-723901.html
文章来源:https://www.toymoban.com/news/detail-723901.html
到了这里,关于android studio虚拟机中一个程序模拟udp通信的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!