从android服务器到python客户端来回发送数据 [英] Sending data back and forth from android server to python client

查看:51
本文介绍了从android服务器到python客户端来回发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天前我已经发布了,但现在我在解决了那个问题后遇到了另一个问题.

I have posted this few days back but now i ran into another problem after solving that one.

描述:使用 kotlin 编写的 android 应用程序作为服务器端运行,Python 程序作为客户端运行在同一台计算机上,并尝试相互发送和接收消息.我正在使用文本视图来显示我从 PC(python) 接收到的消息.

DESCRIPTION: working on an android app written in kotlin that behaves as a server side and Python program that works as a client both runs on same computer and try to send and receive messages from each other.I'm using a text view to display messages that i'm receiving from PC(python).

问题: 每当我尝试在 python 中运行客户端程序时.我在终端上得到以下输出.我没有收到服务器在连接时发送的消息

Problem: whenever i try to run client program in python.I get following output on terminal.I don't get the message that server sends on connection

server sent something.....
 b''
you are about to.....

而在服务器端,它不会从客户端接收任何东西.

whereas on the server side it doesn't receives anything from client.

我尝试过的:我使用端口转发将客户端上的端口 5000 映射到模拟器上的 6000,因为有人建议在上一篇文章中基本上解决了我的错误:61 连接被拒绝 在客户端用 python 编写,但不幸的是我有这个问题.这是因为我在服务器端使用 kotlin 与 python 通信,应该改用 java.或者我使用了错误的线程逻辑.

What i have Tried: I have used port forwarding which maps port 5000 on client to 6000 on emulator as someone suggested that in the previous post which basically solved my error:61 connection refused on client side writen in python but unfortunately i have this problem.Is this because of the fact that i'm using kotlin on server side to communicate with python and should use java instead. Or i'm using wrong thread logic.

请帮帮我

import socket


def main():
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect(('127.0.0.1', 5000))
    while True:
        data = client_socket.recv(1024)
        print("server sent something.....\n", data)
        print("you are about to.....")
        client_socket.sendall(bytes("hey server....", 'utf-8'))
        break
    client_socket.close()


main()

package com.example.soundsource

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.Button
import android.widget.TextView
import java.net.ServerSocket
import java.net.Socket
import java.io.*





class MainActivity : AppCompatActivity() {



    private lateinit var textView:TextView

    companion object{
        const val COMMUNICATIONPORT = 6000
        private lateinit var serversocket:ServerSocket
        private lateinit var serverThread:Thread
        private lateinit var updateConversationHandler:Handler
    }


    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{
//            serverThread = Thread(ServerThread())
//            serverThread.start()
//        }
        serverThread = Thread(ServerThread())
        serverThread.start()
    }

    class ServerThread:Runnable{
        override fun run() {
            var socket: Socket
            try {
                serversocket = ServerSocket(COMMUNICATIONPORT)

            } catch (e:IOException) {
                e.printStackTrace()
            }

            while (!Thread.currentThread().isInterrupted) {

                try {

                    socket = serversocket.accept()
                    val message = "client connected from ${socket.localAddress} and ${socket.localPort}....."
                    MainActivity().textView.text = message
                    val commThread = CommunicationThread(socket)
                    Thread(commThread).start()

                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
        }
    }


    class CommunicationThread(clientSocket: Socket) : Runnable {

        private var input: BufferedReader? = null
        private var output:PrintWriter? = null

        init {

            try {

                input = BufferedReader(InputStreamReader(clientSocket.getInputStream()))
                output = PrintWriter(clientSocket.getOutputStream(),true)

            } catch (e: IOException) {
                e.printStackTrace()
            }

        }

        override fun run() {

            while (!Thread.currentThread().isInterrupted) {

                try {
                    output!!.println("Thanks for connecting with me.....")
                    val read = input!!.readLine()

                    updateConversationHandler.post(MainActivity().UpdateUIThread(read))

                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
        }

    }

    internal inner class UpdateUIThread(private val msg: String) : Runnable {

        override fun run() {
            val message =  "Client Says: $msg \n"
            textView.text = message
        }
    }

}

推荐答案

您的 Android 应用正在侦听端口 6000,而 Python 脚本正在与 5000 通信.还确定您的 Android 具有 localhost 的 IP 吗?

your Android App is listening on Port 6000 and the Python script is talking to 5000. Also sure your Android has IP of localhost ?

这篇关于从android服务器到python客户端来回发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆