sender
Note:

All the inputs here are Strings, the reason is the implementation later on. It’s easier to pass all the parameters as the same type, and they need to be passed in another function because using the network in the main thread is forbidden in Android to avoid to freeze the GUI. For the exceptions, I consider you know what it is, but even if you don’t, just consider they are mandatory. And AS will automatically add them for you if need be (the usual alt + enter).


try {
    DatagramSocket s = new DatagramSocket();
    int length = your_string.length();
    byte[] message = your_string.getBytes();
    InetAddress ip = InetAddress.getByName(the_ip_destination_as_a_string);
    int port = Integer.getInteger(port_destination_as_a_string,default_port_as_an_int); 
    DatagramPacket p = new DatagramPacket(message, length, ip, port);
    s.send(p); 
} catch (UnknownHostException e) {
    e.printStackTrace();
} catch (SocketException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Next Back

The sender
Tagged on:     

2 thoughts on “The sender

Leave a Reply