【问题标题】:kotlin Socket connection regularly sends but does not receive datakotlin Socket连接定时发送但不接收数据
【发布时间】:2022-10-23 17:58:20
【问题描述】:

我正在尝试用 python 中的服务器编写应用程序。 一切都完美连接,字符串是从 android 发送的,但无法从服务器获取字符串。尝试获取字符串时,流被简单地阻塞,如果设置了超时,则简单地调用异常“超时”,这是合乎逻辑的。我已经尝试了所有方法,我将立即向您展示我目前遇到的所有发送和接收代码(同时使用 BufferedReader().ready(),一切正常)

蟒蛇服务器

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(server_address)
server_socket.listen(1)

print ('Waiting for a client connection...')
connection, client_address = server_socket.accept()
print ('Connected to:', client_address)


# listen for data for forever
while True:
    data = connection.recv(data_size)
    print ('Received', data.decode('utf-8')) # print as raw bytes
    sizeOfMainMsg = int(data.decode('utf-8'))
    data = connection.recv(sizeOfMainMsg)
    print ('Received', data.decode('utf-8')) # print as raw bytes
    toSendTry = "Sendet "
    connection.send(bytes(toSendTry,'UTF-8'))

Kotlin 客户端

clientSocket = Socket(SERVER_ADDRESS, SERVER_PORT)


clientSocketOut = clientSocket!!.getOutputStream()
clientSocketIn = clientSocket!!.getInputStream()

if (clientSocket != null) {
while (clientSocketOut != null && clientSocketIn != null && clientSocket!!.isConnected()) {
    var tmp = clientSocketIn!!.bufferedReader(Charsets.UTF_8)
    if(tmp.ready()){
        recived.add(tmp.readLine()) #This is where the problems occur
    }
    if (toSend.size > 0){
        for (nowMsg in toSend){
            clientSocketOut!!.write(nowMsg.toByteArray(Charsets.UTF_8).size.toString().toByteArray(Charsets.UTF_8))
            clientSocketOut!!.flush()
            clientSocketOut!!.write(nowMsg.toByteArray(Charsets.UTF_8))
            clientSocketOut!!.flush()
        }
        toSend.clear()
    }
}

(不用说,kotlin 客户端代码是用 AsyncTask 写的)

【问题讨论】:

  • python服务器在哪里运行?在电脑上?您有一个在 Android 设备上运行的客户端应用程序?
  • 您的客户尝试读取一行。现在为了成功,服务器应该发送一条线。服务器是这样做的吗?一行不仅仅是一个字符串。
  • 服务器当前在 PC 上运行。通过wifi,可以连接到安卓设备。问题是服务器稳定地连接并接收来自android设备的消息并且没有错误。但是没有收到从服务器发送到设备的内容。准确地说,buffer.ready() 变为 true,但一切都在 .readLine() 处停止。服务器定期发送。顺便说一句,是的,我没有具体说明 - 我正在发送从字符串接收的字节数组
  • Through wifi, there is a connection to an android device. ?? Android 设备上的客户端应用程序可以连接到您的 PC 上的服务器是可能发生的事情。
  • the catch is that the server connects 不,客户端可以启动连接。服务器未连接。它一直监听直到客户端连接。

标签: python android kotlin sockets networking


【解决方案1】:

您的客户尝试读取一行。

现在为了成功,服务器应该发送一条线。

一行不仅仅是一个字符串。

【讨论】:

    猜你喜欢
    • 2012-08-05
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    相关资源
    最近更新 更多