-1

I am trying to establish a connection between an android phone(as server) and my computer(client in python) to send messages from the android phone to PC. My Problem is that the app keeps crashing and I don't really know how to set the ip's.

So what I do is when the app opens I give it the computers IP and the port at which I need to send the message and then I click "send button".

Down below I have given the code that I have tried but the app crashes at the socket.send(sendPacket);

Android Code

public class MainActivity extends Activity {

    private EditText ipInput;
    private EditText portInput;
    private EditText messageInput;
    private Button sendButton;
    private DatagramSocket socket;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ipInput = (EditText) findViewById(R.id.address);
        portInput = (EditText) findViewById(R.id.port);
        messageInput = (EditText) findViewById(R.id.message);

        sendButton = (Button) findViewById(R.id.send);
        sendButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String message = messageInput.getText().toString();
                Log.e("TAG",message);
                sendPacket(message);
            }
        });
    }

    private void sendPacket(String message) {
        byte[] messageData = message.getBytes();

        try {
            InetAddress addr = InetAddress.getByName(ipInput.getText().toString());
            int port = Integer.parseInt(portInput.getText().toString());
            DatagramPacket sendPacket = new DatagramPacket(messageData, 0, messageData.length, addr, port);
            if (socket != null) {
                socket.disconnect();
                socket.close();
                return;
            }
            socket = new DatagramSocket(port);
            socket.send(sendPacket);
        } catch (UnknownHostException e) {
            Log.e("MainActivity sendPacket", "getByName failed");
        } catch (IOException e) {
            Log.e("MainActivity sendPacket", "send failed");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        socket.disconnect();
        socket.close();
    }
}

Python Code:

My python code is also there, I bind the IP at 0.0.0.0 so I can get packet from anyone trying to communicate.

from socket import *

PORT = 7000 
IP = "0.0.0.0" 
sock = socket(AF_INET, SOCK_DGRAM) # SOCK_DGRAM means UDP socket
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) 
sock.bind((IP, PORT))
while True:
    print "Waiting for data..."
    data, addr = sock.recvfrom(1024) # blocking
    print "received: " + data

To sum it all up. I really need help with setting ip's, whose ip should I give to the android phone(the phone's or the laptops) and whose ip should I give to the laptop in the python code. Secondly why does the app crash at "socket.send(sendPacket);" inside the send packet method. If you need more details let me know in the comments.

ahsan
  • 23
  • 1
  • 9
  • Please [edit] your question to provide the complete [stack trace from the crash](https://stackoverflow.com/a/23353174). – Mike M. Aug 04 '19 at 23:40

2 Answers2

0

So I can't answer you why the app is crashing but I can answer the IP question.

The client (laptop) needs the servers ip (in the same network its 192.168.X.XXX).
The server (phone) might also need his own ip.
The client might also need his own ip.
But notice that the server doesn't need the clients ip, it's open for all connections (except you want to white/black-list certain ip´s).

Theodor Peifer
  • 3,097
  • 4
  • 17
  • 30
0

I did the same things with just some ip differences, works for me. I have an app on which i press a button and it should turn on/off an led on a raspberry pi.

the code on android studio looks like this :

onPressed: () async {
              setState(() {
                instruction = power;
                power = power == 'on' ? 'off' : 'on';
                print('$instruction');
              });
              int port = 9999;
              final socket = await EasyUDPSocket.bindBroadcast(port);
              if (socket != null) {
                socket.send(ascii.encode('$instruction'), '192.168.0.105', port);
                final resp = await socket.receive();
                print('Client $port received: $resp');

                // `close` method of EasyUDPSocket is awaitable.
                await socket.close();
                print('Client $port closed');
              }
             },

the '192.168.0.105' is the ipv4 address of the raspberry pi(this can be found by typing "ipconfig" for windows in cmd and by "ifconfig" in an rpi)

the python code on the rpi or any pc will be

from socket import *
s = socket(AF_INET, SOCK_DGRAM)
print("socket created")
    
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) 
s.bind(("192.168.0.105",9999))
while True:
    print("Waiting for data...")
    data, addr = s.recvfrom(1024) # blocking
    instruction = data.decode("utf-8")
    if instruction == 'off':
        print('turn off the led')
    else:
        print("turn on the led")

the python code is a bit customized for the led purpose but i'm sure you'll understand how to work with it!