Sending data back and forth from android server to python client

2024/10/9 22:24:45

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

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).

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.

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.

Please help me out

import socketdef 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'))breakclient_socket.close()main()
package com.example.soundsourceimport 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:TextViewcompanion object{const val COMMUNICATIONPORT = 6000private lateinit var serversocket:ServerSocketprivate lateinit var serverThread:Threadprivate 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? ButtonshowLocation?.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: Sockettry {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 = messageval commThread = CommunicationThread(socket)Thread(commThread).start()} catch (e: IOException) {e.printStackTrace()}}}}class CommunicationThread(clientSocket: Socket) : Runnable {private var input: BufferedReader? = nullprivate var output:PrintWriter? = nullinit {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}}}
Answer

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

https://en.xdnf.cn/q/118526.html

Related Q&A

Loop to run 4 times to try run a SQL procedure, after 4 attempts then stop

I have attempted to write some code in python to do a loop 4 times. It will fail as spTest doesnt exist. So I want to try loop again (repeated 4 times total) if it still cant find it, I want to break o…

Loops in Python 3.4.3

I apologize ahead of time for my ignorance but I have trying to code something in python that requires a question to be asked to the user and the user responds. Dependent on that response, the program …

Adding userdata on create VM operation with Python SDK for Azure

I am using Python sdk for azure creation virtual machine operation. I want some script to be executed whenever the VM starts. So, I have tried adding the custom-data while creating VM with Python. My d…

python obtain the self variable in another class which already has a self function

I want to use the self variables in one class and use them in another class which already has its own self variables how to do I do this. Some code here to help.class A():self.health = 5 class B(): # T…

Cannot pip install package in virtualenv on EC2

Im seeing this weird issue on ec2. Im trying to install lsm-db package inside my virtualenv, it says its successfully installed but when trying to import the package or do pip list its not there.I crea…

Python: string to integer as a key

Im trying to convert a string column in a dataframe to int. The strings should be replaced with an integer as a key value.Data:user_id site_id 100 url1.com 100 url2.com 100 url1.com 101…

Data manipulation, kind of downsampling

I have a large csv file, example of the data below. I will use an example of eight teams to illustrate.home_team away_team home_score away_score year belgium france 2…

Chrome Native Messaging throwing error when sending a base64 string to client

Using Chrome Native Messaging sample app as a template am able make a system call to bashos.system("<bash command>")The requirement is to return a base64 string from the python scriptos…

Exporting DataFrame to Excel using pandas without subscribe

How can I export DataFrame to excel without subscribe? For exemple: Im doing webscraping and there is a table with pagination, so I take the page 1 save it in DataFrame, export to excel e do it again …

Fraction of a real number in python giving complicated answer

Importing Fraction from fractions to give a fractional representation of a real number, but giving responses quite complicated which seems very simple by the paper-pen method. Fractions(.2) giving answ…