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

Python 2.7 Socket服务器与Android客户端:无法接收列表数据求助

Let's Diagnose & Fix Your Socket Communication Issue

First, let's break down why your Android client isn't getting the list data from the Python server — there are a few key blocking problems in both codes:

1. Python Server Gets Stuck Waiting for Client Data

Looking at your server code, right after accepting a connection, you call buf = conn.recv(64) — but your Android client never sends any data to the server! This means the server will hang indefinitely waiting for input, and the line that sends your list (send=conn.send(list)) will never run. That's a showstopper right there.

2. Server Closes the Wrong Socket

After sending data, you call s.close() which shuts down the main listening socket, not the connection-specific conn socket. This means after the first connection, your server will crash when it tries to s.accept() again because the listening socket is gone. You should close conn instead.

3. Missing Newline for Android's readLine()

Your Android client uses input.readLine() to read data, which only returns when it hits a newline character (\n). But your Python server sends the list string without any newline — so the client will sit there forever waiting for that newline signal.

4. Android Client's Input Stream Mistakes

  • You're reinitializing BufferedReader every time you click the button, but socket.getInputStream() should only be retrieved once per connection. Reinitializing it can corrupt the stream.
  • You don't check if the socket is actually connected before trying to read from it — if the user clicks the button before the ClientThread finishes connecting, you'll get a NullPointerException.
  • readLine() can return null (if the server closes the connection), and calling toString() on a null value will crash your app.

Fixed Code for Both Sides

Updated Python Server

import socket
import sys
HOST = '192.168.0.108' # Match your local IP
PORT = 8888
# Convert list to string and add a newline for Android's readLine()
list_str = str(["firstitem",'nextitem']) + '\n'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'socket created'
try:
    s.bind((HOST, PORT))
except socket.error as err:
    print 'Bind Failed, Error Code: ' + str(err[0]) + ', Message: ' + err[1]
    sys.exit()
print 'Socket Bind Success!'
s.listen(10)
print 'Socket is now listening'
while 1:
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])
    
    # Remove the recv line if you don't need to get data from the client
    # buf = conn.recv(64)
    # print buf
    
    # Send the list string with a newline
    sent_bytes = conn.send(list_str)
    print 'Sent {} bytes to client'.format(sent_bytes)
    
    print 'Closed connection with ' + addr[0] + ':' + str(addr[1])
    # Close the connection socket, not the listening socket
    conn.close()

Updated Android Client

package com.javacodegeeks.android.androidsocketclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class Client extends Activity {
    private Socket socket;
    private static final int SERVERPORT = 8888;
    private static final String SERVER_IP = "192.168.0.108";
    private BufferedReader input;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        new Thread(new ClientThread()).start();
    }

    public void onClick(View view) {
        // Check if we're actually connected first
        if (socket == null || !socket.isConnected()) {
            Toast.makeText(this, "Not connected to server yet!", Toast.LENGTH_SHORT).show();
            return;
        }
        
        try {
            // Initialize input stream only once per connection
            if (input == null) {
                input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            }
            
            String receivedData = input.readLine();
            if (receivedData != null) {
                Log.d("INFO", "Received: " + receivedData);
                Toast.makeText(this, "Got data: " + receivedData, Toast.LENGTH_SHORT).show();
            } else {
                Log.d("INFO", "Server closed the connection");
                Toast.makeText(this, "Server disconnected", Toast.LENGTH_SHORT).show();
                // Clean up resources
                input.close();
                socket.close();
                socket = null;
                input = null;
            }
        } catch (IOException e) {
            Log.e("ERROR", "Failed to read data", e);
            Toast.makeText(this, "Error reading from server", Toast.LENGTH_SHORT).show();
        }
    }

    class ClientThread implements Runnable {
        @Override
        public void run() {
            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
                socket = new Socket(serverAddr, SERVERPORT);
                Log.d("INFO", "Successfully connected to server");
            } catch (UnknownHostException e1) {
                Log.e("ERROR", "Couldn't find server IP", e1);
                // Show toast on UI thread
                runOnUiThread(() -> Toast.makeText(Client.this, "Unknown server IP", Toast.LENGTH_SHORT).show());
            } catch (IOException e1) {
                Log.e("ERROR", "Connection failed", e1);
                runOnUiThread(() -> Toast.makeText(Client.this, "Failed to connect to server", Toast.LENGTH_SHORT).show());
            }
        }
    }
}

Extra Troubleshooting Steps

  • Verify Network: Make sure both your Python server machine and Android device are on the same WiFi network. Test if your Android device can ping the server's IP (192.168.0.108) (you can use a ping app from the Play Store).
  • Check Firewall: Ensure your server's firewall allows incoming connections on port 8888.
  • Test with Telnet: On your computer, run telnet 192.168.0.108 8888 — you should immediately see the list string appear, which confirms the server is sending data correctly.
  • Debug Logs: Use the Android Studio Logcat and Python console logs to track exactly when connections are made, data is sent, and errors occur.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:49:18