python - 如何使android应用程序作为服务器和python作为客户端
问题描述
描述
所以基本上我正在构建一个android应用程序,我在其中使用kotlin,它将作为服务器运行。而在客户端我使用python。我为此目的使用套接字。我必须使用UDP进行通信。但我无法连接到我的 android 应用程序。在 python 脚本sock.connect(('10.0.2.2', 6000))中,我也尝试放置模拟器 ip 而不是 localhost。我只想发送和接收简单的消息。
另一个问题: Python 脚本只是超时,它甚至没有进入循环。
服务器.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.io.PrintWriter
import java.lang.Exception
import java.lang.ref.WeakReference
import java.net.ServerSocket
import java.net.Socket
class MainActivity : AppCompatActivity() {
private lateinit var textView:TextView
private var message = " "
private lateinit var client:Socket
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{
t.start()
}
}
private val t = Thread(Runnable {
val port = 5000
val server = ServerSocket(port)
this.message = "Message from client"
this@MainActivity.runOnUiThread {
this.textView.text = server.localPort.toString()
}
val i = InputStreamReader(this.client.getInputStream())
val b = BufferedReader(i)
while (true){
this.client = server.accept()
message += " "+ this.client.localAddress.toString()+b.readLine()
this@MainActivity.runOnUiThread{
this.textView.text = server.localSocketAddress.toString()
}
t2.start()
}
})
private val t2 = Thread(Runnable {
val p = PrintWriter(this.client.getOutputStream())
p.println("sending message back")
runOnUiThread {
this.textView.text = "message sent...."
}
})
}
客户端.py
import socket
def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('10.0.2.2', 5000))
while True:
print("you are about to.....")
data = sock.recv(1024)
print('you received :', data)
sock.sendall(bytes("hey kotlin....", 'utf-8'))
main()
解决方案
推荐阅读
- reactjs - 在 cmd 中运行 create-react-app 后未创建新的反应应用程序
- ios - “ContentView.swift”目前被锁定编辑
- javascript - 来自本地主机的多个 .js 调用
- html - 在暗模式下控制 Gmail 中的颜色交换
- java - 如何使用 Java Spring 的泛型类型实现存储库模式
- reactjs - 在控制台中使用 react-hooks useEffect 警告 React Apollo
- python - pands.read_json dtype 对象到整数/数字
- linux - 列表文件中的格式错误的条目 1
- laravel - 您可能需要一个额外的加载器来处理这些加载器的结果
- biopython - 如何从 FASTA 文件中进行多个成对对齐并打印相似度百分比?