无法使用套接字在应用程序和脚本之间进行通信

问题描述

大家好,在此先感谢您抽出宝贵时间来阅读和帮助。

Python:SERVER 科特琳:客户

我正在一个项目中,我必须使用套接字在我的应用程序和python脚本之间进行通信。我面临的问题是我可以从kotlin发送消息并可以在python中读取它,但无法读取该回复从kotlin的python端开始。

我已附上服务器和客户端代码,以帮助您更好地了解

Server.py

import socket


def create_socket():
    server_socket = socket.socket()
    print("Socket successfully created.....")
    server_socket.bind(('localhost',6500))
    return server_socket


def main():
    server_socket = create_socket()
    server_socket.listen(10)
    while True:
        print("socket is listening on port 6500.....")
        client,address = server_socket.accept()
        print('Got connection from',address[0],"on port",address[1]," ....")
        print(client.recv(1024).decode())
        print("Sending response back to client.....")
        client.send("hello from python.....".encode('utf-8'))


main()

Client.kt

package com.example.soundsource

import android.content.Intent
import android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import java.io.BufferedInputStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.Exception
import java.lang.ref.WeakReference
import java.net.socket


class MainActivity : AppCompatActivity() {

    private lateinit var textView:TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val sendButton:Button = findViewById(R.id.send_button)
        val showLocation = findViewById(R.id.show_location) as? Button
        showLocation?.setonClickListener {
            val intent = Intent(this,SoundLocation::class.java)
            startActivity(intent)
        }
        textView = findViewById(R.id.text_view)
        sendButton.setonClickListener{
            val client = Client(this)
            client.execute()
        }
    }

    class Client internal constructor(context:MainActivity):AsyncTask<Void,Void,String?>(){

        private val activityReference: WeakReference<MainActivity> = WeakReference(context)

        override fun doInBackground(vararg params: Void?): String {
            try {
                val socket = Socket("10.0.2.2",6500)
                socket.getoutputStream().write("hello from kotlin.....".toByteArray())
                return receiveMessage(socket)
            }
            catch (exception:Exception){
                 return exception.toString()
            }
        }


       // set text view's text to reply from server 
        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            val activity = activityReference.get()
            if (activity == null || activity.isFinishing)
                return
            activity.textView.text = result
        }

        override fun onPreExecute() {
            super.onPreExecute()
            val activity = activityReference.get()
            if (activity == null || activity.isFinishing)
                return
            activity.textView.text = activity.getString(R.string.pre)
        }

       // receive message from server
        private fun receiveMessage(socket: Socket):String{
            val inputStreamReader = InputStreamReader(socket.getInputStream())
            val  bufferedReader= BufferedReader(inputStreamReader)
            val activity = activityReference.get()
            if (activity == null || activity.isFinishing)
                return ""
            if (bufferedReader.ready())
                return bufferedReader.readLine()
            return " "
        }
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)