简体   繁体   中英

Android - UDP Client Error

I have a little C++/Java - Socket Server (UDP) running on my PC. Now, i want to connect with my Android App to the Server. But when i send a package my App crash.

public void Socketinit() {

    // 1. Socket erstellen!
    try {
        serverAddr = InetAddress.getByName("192.168.0.101");
        socket = new DatagramSocket();

    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    createListeners();


}

and

entprivate void createListeners() {

    confirm.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

            buf = input.getText().toString().getBytes();
DatagramPacket packet = new DatagramPacket(buf,buf.length, serverAddr, SERVERPORT);

            try {
                socket.send(packet);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });

It crashs on "socket.send(packet);" I can connect to my Server via C++ so the Server is up and running. Where is the Clientproblem in my code ?

thanks

You are propably getting the NetworkOnMainThreadException (see Logcat or check in the debugger).

You can use an AsyncTask to resolve this. Propably you are also missing the Internet permission in the manifest.

Here are further details: How to fix android.os.NetworkOnMainThreadException?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM