如何从Android Studio中的Python插座服务器接收输入?

发布于 2025-01-18 10:10:41 字数 1260 浏览 0 评论 0原文

我有一个 python 套接字服务器,它从 Android 应用程序接收一个字符串,并且应该返回相同的大写字符串。应用程序可以发送字符串,我在服务器中接收它,但是我如何在 Android studio 中接收返回的字符串?

这是我的Python代码:

import socket

HOST = "127.0.0.1"  # Standard loopback interface address (localhost)
PORT = 65432  # Port to listen on (non-privileged ports are > 1023)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
    print(f"Connected by {addr}")
    while True:
        data = conn.recv(1024)
        print(data)
        if not data:
            break
        conn.sendall(data.upper())

这是我的发送消息函数

Socket s;
PrintWriter pw;

@Override
protected Void doInBackground(String... voids) {
    String message = voids[0];

    byte[] messageByte = new byte[1000];
    boolean end = false;
    String dataString = "";

    try {
        s = new Socket("10.0.2.2", Integer.parseInt("65432"));
        //sending data
        pw = new PrintWriter(s.getOutputStream());
        pw.write(message);
        pw.flush();
        pw.close();
        //////////
        //receiving data


        s.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

I have a python socket server that receives a string from an Android app and should return the same string in uppercase. The app can send the string and I receive it in the server but how could I receive the returned string in the Android studio?

Here is my python code:

import socket

HOST = "127.0.0.1"  # Standard loopback interface address (localhost)
PORT = 65432  # Port to listen on (non-privileged ports are > 1023)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
    print(f"Connected by {addr}")
    while True:
        data = conn.recv(1024)
        print(data)
        if not data:
            break
        conn.sendall(data.upper())

Here is my sending message function

Socket s;
PrintWriter pw;

@Override
protected Void doInBackground(String... voids) {
    String message = voids[0];

    byte[] messageByte = new byte[1000];
    boolean end = false;
    String dataString = "";

    try {
        s = new Socket("10.0.2.2", Integer.parseInt("65432"));
        //sending data
        pw = new PrintWriter(s.getOutputStream());
        pw.write(message);
        pw.flush();
        pw.close();
        //////////
        //receiving data


        s.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文