简体   繁体   English

从 Android 客户端连续发送数据到 Python 服务器套接字

[英]Continuously Send Data from Android Client to Python Server Socket

I am currently trying to send ble data from the app to my PC using sockets.我目前正在尝试使用 sockets 将应用程序中的 ble 数据发送到我的 PC。 As of now, I am able to send data to the server, but the server only receives one data and then stops receiving.截至目前,我可以向服务器发送数据,但服务器只接收到一个数据,然后停止接收。 I am suspecting that there is something wrong with my client side code.我怀疑我的客户端代码有问题。 Any help would be appreciated任何帮助,将不胜感激

My SocketClass code:我的 SocketClass 代码:

inner class SocketClass{
    fun doInBackground(message: String): String {
        try {
            socket = Socket(SERVER_IP, SERVERPORT)
            val outputStream = OutputStreamWriter(socket?.getOutputStream())
            val printwriter = BufferedWriter(outputStream)
            printwriter.write(message)
            printwriter.flush()
            printwriter.close()
            socket?.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }catch (e: UnknownHostException){

        }
        return ""
    }
}

and in the blereadcharacteristic I call the class in a thread like this:在 blereadcharacteristic 中,我在这样的线程中调用 class:

private fun readDeviceCharacteristic(characteristic: BluetoothGattCharacteristic) {
        var hashval:MutableMap<String, String> = mutableMapOf()
        var mainThreadList :MutableList<String> = mutableListOf()
        var currentTime: String = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS").withZone(
            ZoneId.of("Asia/Seoul")).format(Instant.now())  // Get current Timestamp
        if(idlist.size != 0) {
            readval = characteristic.getStringValue(0)
            valdata = readval.subSequence(3, readval.length).toString()
            idNo = readval.subSequence(0, 2).toString()
            parseList.add(readval)
            mainThreadList = parseList.toMutableList().distinctBy{it.subSequence(0, 2)} as MutableList<String>
            if(mainThreadList.size == maxConnLimit) {
                bleDataList = mainThreadList
                bleDataList.forEach{
                    hashval[it.subSequence(0, 2).toString()] = it.subSequence(3, it.length).toString()
                }
                loghash = hashval.toSortedMap()
                txtRead = bleDataList.toString()
                parseList.clear()
                if(isChecked) {
                    savehash["Time"]?.add("$sec.$millis")
                    bleDataList.forEach {
                        savehash[it.subSequence(0, 2).toString()]?.add(
                            it.subSequence(
                                3,
                                it.length
                            ).toString()
                        )
                    }

                }else{
                    time = 0
                    sec = 0
                    millis = ""
                }
                if(isInsert){
                    Thread{
                        SocketClass().doInBackground("$loghash\r\n\r\n")
                    }.start()
                }

            }
        }
        isTxtRead = true
        bleDataList.clear()
    }

My server socket python code:我的服务器套接字 python 代码:

    import socket
import sys

host = '19.201.12.12'
port = 30001
address = (host, port)

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(address)
server_socket.listen(5)

print("Listening for client . . .")
conn, address = server_socket.accept()
print("Connected to client at ", address)                                                  
while True:
    output = conn.recv(2048);
    if output.strip() == "disconnect":
        conn.close()
        sys.exit("Received disconnect message.  Shutting down.")

    elif output:
        print("Message received from client:")
        print(output)

I am able to get the first data sent, but do not receive anything after.我能够发送第一个数据,但之后什么也没有收到。 Any help would be greatly appreciated thankyou!任何帮助将不胜感激谢谢!

Your server code only accepts one client connection.您的服务器代码只接受一个客户端连接。 So, here's the timelime.所以,这是时间安排。

  1. Python waits at accept . Python 等待accept
  2. Kotlin connects Kotlin 连接
  3. Python moves into while True loop. Python 进入while True循环。
  4. Kotlin writes, then closes the socket. Kotlin 写入,然后关闭套接字。

At that point, nothing further will be received by the Python code, but because you never call accept again, you can't accept another connection.到那时,Python 代码将不会收到任何进一步的信息,但是因为您不再调用accept ,所以您不能接受另一个连接。

You need to have the accept in a loop.您需要循环accept You handle that connection until it closes, then you loop to another accept .您处理该连接直到它关闭,然后您循环到另一个accept

You might consider using the socketserver module, which automates some of this.您可能会考虑使用socketserver模块,它可以自动执行其中的一些操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM