I want to send a UDP message from my Android phone 4.2 (client) to a PC (server) using a WIFI connection. My phone and PC are connected through a wireless router. But from the telephone to the mobile phone no messages are received. I also successfully checked this code to connect PC to PC. I added the internet permission manifest.xml. I would be glad if you could help me. Thank. I added this permission.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Customer:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
final TextView tv = (TextView) findViewById(R.id.textView1);
final TextView tv2= (TextView) findViewById(R.id.textView2);
button1.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
boolean morgan= isOnline();
String s = String.valueOf(morgan);
tv.setText(s);
try{
InetAddress ipaddress = InetAddress.getByName("192.168.10.11");
int port = 6500;
String msg ="hello goooooooogle";
byte [] b_array = msg.getBytes();
DatagramPacket packet = new DatagramPacket(b_array, b_array.length, ipaddress, port);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
socket.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
});
}
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 192.168.10.11");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
}
catch (IOException e)
{ e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
return false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
Server
public class server
{
public static void main(String args[])
{
try{
System.out.println("aaa");
byte[] inbuf = new byte[1000];
DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
DatagramSocket socket = new DatagramSocket(6500);
socket.receive(packet);
int numBytesReceived = packet.getLength();
System.out.println(numBytesReceived);
String s = new String(inbuf);
System.out.println(s);
socket.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
source
share