Enviar mensaje udp desde el teléfono android a la PC (windows) no funciona
Quiero enviar un mensaje UDP desde mi teléfono Android 4.2 (cliente) a la PC (servidor) mediante la conexión WIFI. Mi teléfono y mi PC están conectados a través de un enrutador inalámbrico. Pero no se recibe ningún mensaje de teléfono a móvil. También he probado este código para la conexión de PC a PC con éxito. He añadido permiso de Internet a manifest.xml. Yo sería greatefull, si usted podría ayudarme. Gracias. He añadido este permiso.
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Cliente:
- Descubrimiento del servicio de red error de tutorial android: Servicio perdido, el teléfono se desactiva
- ¿Es esta la forma correcta de iniciar una actividad?
- Tabs + Deslizar en Android para todos los niveles de API
- Tienes problemas para conectarte a Google Play Services; Obtener el código de estado Cancelado
- Android.os.NetworkOnMainThreadException usando rxjava en android
@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("localhost"); InetAddress ipaddress = InetAddress.getByName("192.168.10.11"); int port = 6500; //byte[] buffer = new byte[1024]; // empty byte array String msg ="hello goooooooogle"; // send this message to the server byte [] b_array = msg.getBytes(); //on SERVER side DatagramSocket able to receive packets on 8080 port DatagramPacket packet = new DatagramPacket(b_array, b_array.length, ipaddress, port);// DatagramPacket(byte[], byte_length, InetAddress, port_number) 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"); //Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8"); 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) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
Servidor
public class server { public static void main(String args[]) { try{ System.out.println("aaa"); byte[] inbuf = new byte[1000]; // default size 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); //System.out.println(inbuf[2]); socket.close(); } catch(Exception e) { System.out.println(e); } } }
- Android y Dalvik - Obtener el tamaño de un objeto
- Android: SortedList con duplicados
- Android: fugas de memoria al crear dinámicamente UI con fondos de recursos de imagen
- Cómo "esperar" un hilo en Android
- Android MediaRecorder produce video corrupto con líneas verdes
- Ejemplos de FacebookSDK Ejemplo no funciona en el teléfono Android
- Android: ¿Notification.DEFAULT_VIBRATE requiere permiso de vibración?
- Compartir Bitmap () en android para twitter, facebook, correo
Cuando se trata de operaciones de red en Android, se recomienda utilizar un hilo separado para realizar dichas operaciones. Intente aislar su código en el método onClick()
en un AsyncTask
para ejecutarlo en segundo plano.
private class SendMessageTask extends AsyncTask<String, Void, Void> { protected Void doInBackground(String... ip) { // run network socket code here return null; } }
Entonces onClick () contendrá algo como esto:
new SendMessageTask().execute("IP_HERE");
Obviamente, usted puede modificarlo para satisfacer sus necesidades. Sin embargo, si necesita enviar más datos durante la duración de su aplicación, puede que desee utilizar su propio hilo de fondo. Esta es una explicación más detallada de por qué las operaciones de red no pueden / no deben hacerse en el subproceso de la interfaz de usuario: http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html
- Teclado rápidamente se oculta y reaparece en Android usando Xamarin Forms
- Reemplazar la aplicación de Android que tiene el mismo nombre de paquete pero nueva keystore