首页 > 解决方案 > 如何使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()

标签: pythonandroidkotlinserversocket

解决方案


推荐阅读