Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package cpe.moi.hello.iotprojet;
- import androidx.appcompat.app.AppCompatActivity;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.text.Editable;
- import android.text.TextWatcher;
- import android.widget.EditText;
- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- public class MainActivity extends AppCompatActivity {
- private String IP;
- private int PORT;
- private InetAddress address;
- private DatagramSocket udpSocket;
- public String message;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- //Todo: change ip
- EditText txtIP = findViewById(R.id.editText);
- EditText txtPORT = findViewById(R.id.editText2);
- txtIP.addTextChangedListener(new TextWatcher() {
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- }
- @Override
- public void afterTextChanged(Editable s) {
- IP = s.toString();
- }
- });
- txtPORT.addTextChangedListener(new TextWatcher() {
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- }
- @Override
- public void afterTextChanged(Editable s) {
- PORT = Integer.valueOf(s.toString());
- }
- });
- }
- private void sendPacket() {
- (new Thread() {
- public void run() {
- try{
- udpSocket = new DatagramSocket();
- address = InetAddress.getByName(IP);
- byte[] data = message.getBytes();
- DatagramPacket packet = new DatagramPacket(data, data.length, address, PORT);
- udpSocket.send(packet);
- } catch(IOException e){
- e.printStackTrace();
- }
- }
- }).start();
- }
- private class ReceiverTask extends AsyncTask<Void, byte[], Void> {
- @Override
- protected Void doInBackground(Void... voids) {
- while(true){
- byte[] data = new byte [1024];
- DatagramPacket packet = new DatagramPacket(data, data.length);
- udpSocket.receive(packet);
- int size = packet.getLength();
- publishProgress(java.util.Arrays.copyOf(data, size));
- }
- }
- protected void onProgressUpdate(byte[]... data){
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement