要实现Android从Python服务器接收消息,你可以使用Socket编程来建立一个TCP连接。以下是一个基本的示例代码:
在Android端:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private static final String SERVER_IP = "your_server_ip";
private static final int SERVER_PORT = 12345;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
try {
Socket socket = new Socket(SERVER_IP, SERVER_PORT);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = reader.readLine();
// 在这里处理接收到的消息
Log.d("Received Message", message);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
在Python服务器端:
import socket
SERVER_IP = 'your_server_ip'
SERVER_PORT = 12345
def main():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((SERVER_IP, SERVER_PORT))
server_socket.listen(1)
print('Server listening on {}:{}'.format(SERVER_IP, SERVER_PORT))
while True:
client_socket, client_address = server_socket.accept()
print('Connection from:', client_address)
message = 'Hello from Python server!'
client_socket.sendall(message.encode())
client_socket.close()
if __name__ == '__main__':
main()
请确保将your_server_ip
替换为你的服务器IP地址,并确保Android设备和Python服务器在同一个网络下。