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

Android Socket空指针异常求助:客户端向服务端传图失败

Hey there! Let's dig into why you're seeing that "Something wrong: null" toast when trying to send images via Socket. Let's break down the possible issues and fixes step by step:

1. Client Socket Initialization Bug

Looking at your ClientRxThread code, there's a clear mismatch in how you're initializing the Socket:

private inner class ClientRxThread internal constructor(internal var dstAddress: String, internal var dstPort: Int) : Thread() { 
    override fun run() { 
        var socket: Socket? = null 
        try { 
            socket = Socket(serverIp, 8080) // Problem here!
            // ... rest of code
        }
    }
}

You defined dstAddress and dstPort as thread parameters but aren't using them—instead, you're referencing an uninitialized serverIp variable. If serverIp is null, creating the Socket will throw an IOException with a null message, which explains your toast.

Fix: Use the parameters you already pass to the thread:

socket = Socket(dstAddress, dstPort)

Make sure when you start this thread, you pass the exact server IP (from the server's infoIp display) and port 8080.

2. Missing Permissions

Android requires explicit permissions for network access and external storage operations. If these aren't set up, your app will fail silently or throw vague exceptions.

First, add these to your AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

For Android 6.0 (API 23+) and above, you also need to request these permissions dynamically at runtime. Add this code to your MainActivity:

private fun checkRequiredPermissions() {
    val permissions = arrayOf(
        Manifest.permission.INTERNET,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
    val missingPermissions = permissions.filter {
        ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
    }
    if (missingPermissions.isNotEmpty()) {
        ActivityCompat.requestPermissions(this, missingPermissions.toTypedArray(), 100)
    }
}

Call checkRequiredPermissions() in onCreate() before starting any socket threads.

3. Verify Server File Exists

In your server's FileTxThread, you're trying to read my_pic.png from external storage:

val file = File(Environment.getExternalStorageDirectory(), "my_pic.png")

If this file doesn't exist, it will throw a FileNotFoundException, which can cause the socket connection to drop unexpectedly. Add a quick check to avoid this:

if (!file.exists()) {
    this@MainActivity.runOnUiThread {
        Toast.makeText(this@MainActivity, "Source file not found!", Toast.LENGTH_LONG).show()
    }
    return
}

4. Confirm Network & IP Setup

Ensure both your client and server devices are connected to the same local network (e.g., same Wi-Fi). Double-check that the IP address displayed in the server's infoIp text view is the exact one you're passing to the client thread—sometimes devices have multiple network interfaces, so pick the correct SiteLocalAddress entry.

5. Clean Up Socket Closure

In both client and server code, you're closing the socket multiple times (once in the try block, once in finally). This can trigger unnecessary exceptions. Simplify the finally block to only close if the socket is still open:

finally {
    socket?.let {
        try {
            if (!it.isClosed) {
                it.close()
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}

Try these fixes one by one—chances are the first one will resolve your immediate "null" error!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:47:45