You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python服务器与Android客户端Socket双向通信:客户端收不到消息

双向Socket连接问题:Android客户端无法接收服务器返回消息

我正在实现Python服务器与Android客户端之间的双向Socket连接,目前服务器可正常接收客户端发送的消息,但Android客户端无法接收或正确处理服务器返回的消息。启动应用后,Python服务器能正确接收客户端发送的"Berlino"消息,但Android端无法获取服务器返回的"Server 123"。用Python客户端测试服务器时可以正常接收返回消息,我需要让Android代码的Log中能打印出接收到的消息。

更新:已在服务器返回的消息中添加换行符,现在Logcat可以看到"mex"日志,但代码卡在receiveDataFromServer()函数的while循环中。


客户端Kotlin代码

MainActivity.kt

package com.example.server_continuous

import android.os.AsyncTask
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import java.util.concurrent.ExecutionException

@Suppress("DEPRECATION")
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val host = "192.168.0.***"
        val port = 8888
        val dataToSend = "Berlino"

        val netClient = NetClient(host, port)
        val result = try {
            SendDataTask().execute(netClient, dataToSend).get()
        } catch (e: InterruptedException) {
            e.printStackTrace()
            "Error: ${e.message}"
        } catch (e: ExecutionException) {
            e.printStackTrace()
            "Error: ${e.message}"
        }
        Log.d("Result",result)

        // Process the result as needed
        println(result)
    }

    inner class SendDataTask : AsyncTask<Any, Void, String>() {
        override fun doInBackground(vararg params: Any): String {
            val netClient = params[0] as NetClient
            val dataToSend = params[1] as String

            netClient.sendDataWithString(dataToSend)
            return netClient.receiveDataFromServer()
        }
    }

}

NetClient.kt

package com.example.server_continuous


import android.util.Log
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.Socket

class NetClient(private val host: String, private val port: Int) {

    companion object {
        const val BUFFER_SIZE = 30
    }

    private var socket: Socket? = null
    private var out: PrintWriter? = null
    private var `in`: BufferedReader? = null

    private fun connectWithServer() {
        try {
            if (socket == null) {
                socket = Socket(host, port)
                out = PrintWriter(socket!!.getOutputStream(), true)
                `in` = BufferedReader(InputStreamReader(socket!!.getInputStream()))
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun disConnectWithServer() {
        if (socket != null) {
            if (socket!!.isConnected) {
                try {
                    `in`?.close()
                    out?.close()
                    socket?.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }

    fun sendDataWithString(message: String) {
        if (message != null) {
            connectWithServer()
            out?.write(message)
            out?.flush()
        }
    }

    fun receiveDataFromServer(): String {
        return try {
            val response = StringBuilder() // Use StringBuilder to efficiently build the response

            connectWithServer()
            var line: String? = null

            // Read the response line by line
            while (`in`?.readLine().also { line = it } != null) {
                println("Message: $line")
                line?.let { Log.d("mex", it) }
                response.append(line) // Append each line to the StringBuilder
            }

            disConnectWithServer()
            response.toString() // Convert the StringBuilder to a String and return the response
        } catch (e: IOException) {
            "Error receiving response: ${e.message}"
        }
    }

}

服务器Python代码

import socket
import json
import threading


# Define the server's IP address and port number
server_ip = socket.gethostbyname(socket.gethostname())
server_port = 8888


# Create a socket object (standard options)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print('Socket created')

# Bind the socket to the IP address and port
try:
    server_socket.bind((server_ip, server_port))
except socket.error as err:
    print('Bind failed, error code:', err)

print('Socket bind success')

# Listen for incoming connections
server_socket.listen(1)  # Listen for only one client connection
print('Server listening on {}:{}'.format(server_ip, server_port))

# Variable to store the connected client socket
client_socket = None

# Flag to indicate server termination
terminate = False

# Function for handling individual client connections
def handle_client():
    global client_socket
    global received_data

    while True:
        if client_socket:
            # Receive data from the client
            data = client_socket.recv(1024).decode('utf-8')
            client_socket.sendall("Server 123\n".encode('utf-8'))  # 已添加换行符
            if not data:
                break

            print('Received from client:', data)

                            

    # # Client connection closed
    # if client_socket:
    #     client_socket.close()
    # client_socket = None

# Function for accepting client connection
def accept_connection():
    global client_socket
    global terminate

    while not terminate:
        try:
            # Accept client connection
            # Client socket and address allow us to reply back to the client
            client_socket, client_address = server_socket.accept()
            print('Connected to client:', client_address)

            # Start a thread for handling the client connection
            client_thread = threading.Thread(target=handle_client,daemon=True)
            client_thread.start()

            # Wait for the client thread to complete
            client_thread.join()

            # # Close the client socket
            # if client_socket:
            #     client_socket.close()
            # client_socket = None
        except KeyboardInterrupt:
            # Terminate the server on keyboard interrupt - DOES NOT WORK
            terminate = True

# Start a thread for accepting client connection
accept_thread = threading.Thread(target=accept_connection,daemon=True)
accept_thread.start()

try:
    # Wait for the accept thread to complete
    accept_thread.join()
except KeyboardInterrupt:
    # Terminate the server on keyboard interrupt - DOES NOT WORK
    terminate = True

# Close the server socket
server_socket.close()
print('Server connection closed')

内容的提问来源于stack exchange,提问作者Fabio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 14:34:55