I wrote a simple server program to try to receive an UDP datagram packet on an android phone. There is a client program that sends out datagram packet. However socket.receive() only works when the client is running on the same phone sending the packet to localhost ip. The datagram socket seem to be unable to receive packets send from other phones.
Below is the code for the server
public class wateverActivity extends Activity {
static DatagramSocket socket;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
socket = new DatagramSocket(11111);
byte[] receiveData = new byte[512];
DatagramPacket datagram = new DatagramPacket(receiveData, 0, receiveData.length,null, 0);
try{
socket.receive(datagram);
String data = new String(datagram.getData());
Toast.makeText(getBaseContext(),"datagram received = " + data,Toast.LENGTH_LONG).show();
}
catch(IOException e)
{
Toast.makeText(getBaseContext(),"I/O Exception",Toast.LENGTH_LONG).show();
}
}
catch(SocketException e)
{
Toast.makeText(getBaseContext(),"Socket Exception",Toast.LENGTH_LONG).show();
}
socket.close();
Toast.makeText(getBaseContext(),"Socket close",Toast.LENGTH_LONG).show();
}
}
Below is the client code
public class UdpClient extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
runUdpClient();
finish();
}
private static final int UDP_SERVER_PORT = 11111;
private void runUdpClient() {
String udpMsg = "hello world from UDP client " + UDP_SERVER_PORT;
DatagramSocket ds = null;
try {
ds = new DatagramSocket();
InetAddress serverAddr = InetAddress.getByName("127.0.0.1");
DatagramPacket dp;
dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), serverAddr, UDP_SERVER_PORT);
ds.send(dp);
} catch (SocketException e) {
e.printStackTrace();
}catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
}
}
for both code i have include internet permission under the manifest file. However the server is still unable to receive any datagram packet.