How to make UDP connection in Android

I am trying to establish a connection between my galaxy tab and laptop . Therefore, I am trying to start server activity on my laptop and client activity on my tab, but this does not work. Here is the server and client code. Where is the mistake?

SERVER:

 public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView txt = (TextView)findViewById(R.id.textView1); int port = 12345; byte [] message = new byte [1500]; DatagramPacket p = new DatagramPacket (message,message.length); try { InetAddress serveraddr = InetAddress.getByName("192.168.1.116"); DatagramSocket s = new DatagramSocket (port,serveraddr); while (true){ s.receive(p); String text = new String (message,0,p.getLength()); txt.setText(text); } } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 

CUSTOMER:

 public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText edt = (EditText)findViewById(R.id.editText1); Button btn = (Button)findViewById(R.id.button1); btn.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { String msg = edt.getText().toString(); int port = 12345; try { DatagramSocket s = new DatagramSocket(); InetAddress local = InetAddress.getByName("192.168.1.116"); int msg_lenght = msg.length(); byte []message = msg.getBytes(); DatagramPacket p = new DatagramPacket(message,msg_lenght,local,port); s.send(p); } catch (SocketException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); } 

Here is the log :

09-17 23: 49: 55.190: D / dalvikvm (5892): check late inclusionJNI 09-17 23: 49: 55.690: D / CLIPBOARD (5892): hide the clipboard dialog box at initial input: completed by someone else. ..! 09-17 23: 49: 59.590: D / AndroidRuntime (5892): shutdown the virtual machine 09-17 23: 49: 59.590: W / dalvikvm (5892): threadid = 1: thread terminates with an unhandled exception (group = 0x40c4f1f8) 09 -17 23: 49: 59.590: E / AndroidRuntime (5892): EXCLUSIVE EXCLUSION: main 09-17 23: 49: 59.590: E / AndroidRuntime (5892): android.os.NetworkOnMainThreadException 09-17 23: 49: 59.590: E / AndroidRuntime (5892): in android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork (StrictMode.java:1099) 09-17 23: 49: 59.590: E / AndroidRuntime (5892): in libcore.io.BlockGuardOs.sendto (BlockGuardOs Java: 175) 09-17. 23: 49: 59.590: E / AndroidRuntime (5892): on libcore.io.IoBridge.sendto (IoBridge.java:463) 09-17 23: 49: 59.590: E / AndroidRuntime (5892): on java.net.PlainDatagramSocketImocket .send (PlainDatagramSocketImpl.java:182) 09-17 23: 49: 59.590: E / AndroidRuntime (5892): on java.net.DatagramSocket.send (DatagramSocket.java:307) 09-17 23: 49: 59.590: E / AndroidRuntime (5892): on com.example.udpclient.MainActivity $ 1.onClick (MainActivity.java:36) 09-17 23: 49: 59.590: E / Androi dRuntime (5892): on android.view.View.performClick (View.java:3620) 09-17 23: 49: 59.590: E / Android Runtime (5892): on android.view.View $ PerformClick.run (View.java: 14322) 09-17. 23: 49: 59.590: E / AndroidRuntime (5892): on android.os.Handler.handleCallback (Handler.java:605) 09-17 23: 49: 59.590: E / AndroidRuntime (5892): on android.os.Handler .dispatchMessage (Handler.java:92) 09-17 23: 49: 59.590: E / AndroidRuntime (5892): on android.os.Looper.loop (Looper.java:137) 09-17 23: 49: 59.590: E / AndroidRuntime (5892): on android.app.ActivityThread.main (ActivityThread.java:4507) 09-17 23: 49: 59.590: E / AndroidRuntime (5892): on java.lang.reflect. Method.invokeNative (native method) 09-17 23: 49: 59.590: E / AndroidRuntime (5892): at java.lang.reflect.Method.invoke (Method.java∗11) 09-17 23: 49: 59.590: E / AndroidRuntime (5892): on com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:978) 09-17 23: 49: 59.590: E / AndroidRuntime (5892): on com.android.internal . os.ZygoteInit.main (ZygoteInit.java:745) 09-17 23:49:59 .590: E / AndroidRuntime (5892): at dalvik.system.NativeStart.main (native method) 09-17 23: 50: 34.320 : I / Process (5892): send a signal. PID: 5892 SIG: 9

+4
source share
4 answers
 09-17 23:49:59.590: E/AndroidRuntime(5892): android.os.NetworkOnMainThreadException 09-17 23:49:59.590: E/AndroidRuntime(5892): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099) 09-17 23:49:59.590: E/AndroidRuntime(5892): at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175) 

You should not perform network or intensive operations on the ui string

See also: Android: NoClassDefFoundError for some app users or Android developer info

order: activity.runOnUi

+4
source

You have an infinite loop in onCreate Server. You should not! Create a thread to poll the socket.

0
source

There are 2 problems with your code.

  1. Networking in the main thread (user interface thread)

09-17 23: 49: 59.590: E / AndroidRuntime (5892): EXCLUSIVE EXCLUSION: basic 09-17 23: 49: 59.590: E / AndroidRuntime (5892): android.os.NetworkOnMainThreadException

  1. while(true) in the main thread:

     while(true) { s.receive(p); String text = new String (message,0,p.getLength()); txt.setText(text); } 
0
source
  • you cannot send udp packets to the ui stream, so you need to create a new separate stream.

Just a quick fix ...

create the udpOutputData line:
String udpOutputData;

create a new thread in your code:

  //-----UDP send thread Thread udpSendThread = new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(100); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (sendUdp == true) { try { // get server name InetAddress serverAddr = InetAddress.getByName(outputIP); Log.d("UDP", "C: Connecting..."); // create new UDP socket DatagramSocket socket = new DatagramSocket(); // prepare data to be sent byte[] buf = udpOutputData.getBytes(); // create a UDP packet with data and its destination ip & port DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, broadcastPort); Log.d("UDP", "C: Sending: '" + new String(buf) + "'"); // send the UDP packet socket.send(packet); socket.close(); Log.d("UDP", "C: Sent."); Log.d("UDP", "C: Done."); } catch (Exception e) { Log.e("UDP", "C: Error", e); } try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } sendUdp = false; } } } }); 

create a method to call every time you want to send some udp data:

  public void sendUdp(String udpMsg) { udpOutputData = udpMsg; sendUdp = true; } 

call the method and pass a line for the output every time you want to send the udp packet:

 String s = "hello from app"; sendUdp(s); 
0
source

Source: https://habr.com/ru/post/1434794/


All Articles