You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android通过Socket向服务器发送数据包及代码闪退问题求助

Fixing Socket Packet Crash on Android 4.2.2 (Samsung GT-P5210)

Hey there! Let's sort out this crash you're hitting when sending packets over Socket on your Samsung Galaxy GT-P5210 running Android 4.2.2. Since you've already got WiFi P2P connected, let's walk through the most common issues and fixes step by step.

Common Crash Causes & Solutions

1. Network Operations on Main Thread (Most Likely Culprit)

Android 4.0 and later strictly prohibits network calls on the UI thread—doing so triggers a NetworkOnMainThreadException and crashes your app immediately. You must offload Socket work to a background thread.

Use an AsyncTask (ideal for simple background tasks on older Android versions) or a dedicated Thread:

// AsyncTask to handle Socket sending safely in background
private class SocketSenderTask extends AsyncTask<String, Void, Boolean> {
    private String remoteIp;
    private static final int SOCKET_PORT = 8888; // Match your server's port

    public SocketSenderTask(String remoteIp) {
        this.remoteIp = remoteIp;
    }

    @Override
    protected Boolean doInBackground(String... messages) {
        Socket clientSocket = null;
        OutputStream outStream = null;

        try {
            // Establish Socket connection to the remote device
            clientSocket = new Socket(remoteIp, SOCKET_PORT);
            outStream = clientSocket.getOutputStream();

            // Send your data (convert string to bytes, adjust for your packet format)
            byte[] packet = messages[0].getBytes();
            outStream.write(packet);
            outStream.flush();

            // If you need to read a response, uncomment this section (and handle properly!)
            // InputStream inStream = clientSocket.getInputStream();
            // byte[] responseBuffer = new byte[1024];
            // int bytesRead = inStream.read(responseBuffer);
            // String response = new String(responseBuffer, 0, bytesRead);
            // Process response here...

            return true;
        } catch (IOException e) {
            e.printStackTrace(); // Check logcat for exact error details
            return false;
        } finally {
            // Always close streams and Socket to avoid resource leaks
            try {
                if (outStream != null) outStream.close();
                if (clientSocket != null) clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onPostExecute(Boolean success) {
        // Update UI after task completes (safe to run on main thread)
        if (success) {
            Toast.makeText(getApplicationContext(), "Packet sent successfully!", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "Failed to send packet. Check logcat for details.", Toast.LENGTH_SHORT).show();
        }
    }
}

To use this task:

// Replace with your WiFi P2P remote device's IP address
String remoteDeviceIp = "192.168.49.1"; // Example P2P IP
new SocketSenderTask(remoteDeviceIp).execute("Your packet data here");

2. Missing Permissions

Ensure your AndroidManifest.xml includes all required permissions for network and WiFi P2P:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

For Android 4.2.2, static permissions are sufficient—no need for dynamic runtime requests.

3. Improper Stream Handling

Your commented-out InputStream code suggests you might have hit issues with unclosed streams or unhandled exceptions. Always:

  • Wrap all Socket/stream operations in try-catch blocks to catch IOException (the #1 cause of unhandled crashes here)
  • Close streams and Socket in a finally block to guarantee cleanup, even if an error occurs
  • If you need to read a response, don't leave the input stream hanging—read it fully or close it promptly

4. Verify WiFi P2P Connection State

Before creating a Socket, confirm the WiFi P2P connection is active. Use WiFiP2pManager.ConnectionInfoListener to listen for successful connections, and only trigger Socket operations once you have a valid WiFiP2pInfo object (with the remote device's IP).

Quick Debug Tip

Check your device's logcat for the exact crash stack trace—this will tell you if it's a NetworkOnMainThreadException, ConnectException, or another issue. That's the fastest way to pinpoint the root cause!

内容的提问来源于stack exchange,提问作者Gary Armstrong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:20:18