Social

Tuesday, August 27, 2013

Sending UDP broadcast socket Messages (Android | Java)

What is a broadcast message?
  • If you want to send some message to every node on your network, that is a broadcast message.
What UDP?
  • With UDP, computer applications can send messages, in this case referred to as datagrams, to other hosts on an Internet Protocol (IP) network without prior communications to set up special transmission channels or data paths. UDP uses a simple transmission model with a minimum of protocol mechanism. It has no handshaking dialogues, and thus exposes any unreliability of the underlying network protocol to the user's program.


So How to design it?
  • Assume that there is 1 sever node and some several client nodes. Server node is the one who broadcasting message. Clients are getting those messages. So here are code parts,


Server Node:

String messageStr="Hello ! This is your msg from server.";
int server_port = 50008; //port that I’m using
try{
DatagramSocket s = new DatagramSocket();
InetAddress local = InetAddress.getByName("192.168.1.255");//my broadcast ip
int msg_length=messageStr.length();
byte[] message = messageStr.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length,local,server_port);
s.send(p);
Log.d("rockman","message send");
}catch(Exception e){
Log.d("rockman","error  " + e.toString());
}


Client Node:


new Thread( new Runnable(){
public void run(){
String text;
int server_port = 50008; 
byte[] message = new byte[1500];
try{
DatagramPacket p = new DatagramPacket(message, message.length);
DatagramSocket s = new DatagramSocket(server_port);
s.receive(p);
text = new String(message, 0, p.getLength());
Log.d("rockman","message:" + text);
s.close();
}catch(Exception e){
Log.d("rockman","error  " + e.toString());
}
}
}).start();



2 comments:

  1. Hello.

    If I send UDP Broadcast from VB.NET 'Receiver' (s.receive(p);) don't work.
    Have Android any restricted, if Broadcast send from PC?

    ReplyDelete
  2. Sending Udp Broadcast Socket Messages (Android >>>>> Download Now

    >>>>> Download Full

    Sending Udp Broadcast Socket Messages (Android >>>>> Download LINK

    >>>>> Download Now

    Sending Udp Broadcast Socket Messages (Android >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete

 

Search This Blog

Most Reading

Protected by Copyscape Duplicate Content Software

Facebook Page