Я новичок в разработке для Android. У меня есть сервер и клиентское приложение. Я пытался отправить изображение из клиентского приложения в серверное приложение, используя сокет, вот код моего клиентского приложения:
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)
val file = File(Environment.getExternalStorageDirectory().absolutePath, "test.png")
val ois = ObjectInputStream(socket.getInputStream())
val bytes: ByteArray
var fos: FileOutputStream? = null
try {
bytes = ois.readObject() as ByteArray
fos = FileOutputStream(file)
fos.write(bytes)
} catch (e: ClassNotFoundException) {
// TODO Auto-generated catch block
e.printStackTrace()
} finally {
fos?.close()
}
socket.close()
this@MainActivity.runOnUiThread {
Toast.makeText(this@MainActivity,
"Finished",
Toast.LENGTH_LONG).show()
}
} catch (e: IOException) {
e.printStackTrace()
val eMsg = "Something wrong: " + e.message
this@MainActivity.runOnUiThread {
Toast.makeText(this@MainActivity,
eMsg,
Toast.LENGTH_LONG).show()
}
} finally {
if (socket != null) {
try {
socket.close()
} catch (e: IOException) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
}
}
}
код приложения моего сервера:
class MainActivity : AppCompatActivity() {
private lateinit var infoIp: TextView
internal lateinit var infoPort: TextView
internal var serverSocket: ServerSocket? = null
private lateinit var serverSocketThread: ServerSocketThread
private val ipAddress: String
get() {
var ip = ""
try {
val enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces()
while (enumNetworkInterfaces.hasMoreElements()) {
val networkInterface = enumNetworkInterfaces
.nextElement()
val enumInetAddress = networkInterface
.inetAddresses
while (enumInetAddress.hasMoreElements()) {
val inetAddress = enumInetAddress.nextElement()
if (inetAddress.isSiteLocalAddress) {
ip += ("SiteLocalAddress: "
+ inetAddress.hostAddress + "\n")
}
}
}
} catch (e: SocketException) {
e.printStackTrace()
ip += "Something Wrong! " + e.toString() + "\n"
}
return ip
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
infoIp = findViewById<TextView>(R.id.infoip)
infoPort = findViewById<TextView>(R.id.infoport)
infoIp.text = ipAddress
serverSocketThread = ServerSocketThread()
serverSocketThread.start()
}
override fun onDestroy() {
super.onDestroy()
if (serverSocket != null) {
try {
serverSocket!!.close()
} catch (e: IOException) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
}
inner class ServerSocketThread : Thread() {
override fun run() {
var socket: Socket? = null
try {
serverSocket = ServerSocket(SocketServerPORT)
this@MainActivity.runOnUiThread(Runnable { infoPort.text = "I'm waiting here: " + serverSocket!!.localPort })
while (true) {
socket = serverSocket!!.accept()
val fileTxThread = FileTxThread(socket)
fileTxThread.start()
}
} catch (e: IOException) {
// TODO Auto-generated catch block
e.printStackTrace()
} finally {
if (socket != null) {
try {
socket.close()
} catch (e: IOException) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
}
}
}
inner class FileTxThread internal constructor(internal var socket: Socket) : Thread() {
override fun run() {
val file = File(
Environment.getExternalStorageDirectory(),
"my_pic.png")
val bytes = ByteArray(file.length().toInt())
val bis: BufferedInputStream
try {
bis = BufferedInputStream(FileInputStream(file))
bis.read(bytes, 0, bytes.size)
val oos = ObjectOutputStream(socket.getOutputStream())
oos.writeObject(bytes)
oos.flush()
socket.close()
val sentMsg = "File sent to: " + socket.inetAddress
this@MainActivity.runOnUiThread(Runnable {
Toast.makeText(this@MainActivity,
sentMsg,
Toast.LENGTH_LONG).show()
})
} catch (e: FileNotFoundException) {
// TODO Auto-generated catch block
e.printStackTrace()
} catch (e: IOException) {
// TODO Auto-generated catch block
e.printStackTrace()
} finally {
try {
socket.close()
} catch (e: IOException) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
}
}
companion object {
internal val SocketServerPORT = 8080
}
}
но во время выполнения, когда я нажимаю кнопку отправки, я получаю исключение (что-то не так: ноль) через тост-сообщение. Я не знаю, что я пропустил или делаю неправильно.
Вот logcat во время отправки:
01-19 01:33:52.367 244-564/? V/AudioPolicyManagerBase: setOutputDevice() setting same device 0000 or null device for output 2
01-19 01:33:55.227 783-977/? E/xxxxxxbtsdcard: checkUser: useridlist=null, currentuser=0
01-19 01:33:55.227 783-977/? E/xxxxxxbtsdcard: checkUser: useridlist=null, currentuser=0
01-19 01:33:55.237 783-977/? E/xxxxxxbtsdcard: checkUser: useridlist=null, currentuser=0
01-19 01:33:55.237 783-977/? E/xxxxxxbtsdcard: checkUser: useridlist=null, currentuser=0
01-19 01:33:56.577 3765-3765/? D/wear: [wear] connection failed, ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null}
01-19 01:33:56.577 3765-3864/? D/wear: [wear] google api client connection failed, null, null