【问题标题】:How do i translate this code into a Android app code我如何将此代码转换为 Android 应用程序代码
【发布时间】:2017-10-04 12:11:07
【问题描述】:

它只是一个与 python 服务器交互的简单 python 客户端,我现在正在尝试在 Android 应用程序上实现以下代码,但我是 Android 新手,有什么帮助吗?

import socket
import json

host='127.0.0.1'
port=9090
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host,port))


while True:
   data = "Message to send"
   sock.send(data)
   response = json.loads(sock.recv(1024))
   print response
   sock.close()
   quit()

我现在有这个,因为它在 Fragment 上运行,我必须创建一个新线程,因为不应该在 UI 线程上完成连接。

class ClientThread implements Runnable {

@Override
 public void run() {
    final String msg = "message to send";
    Log.d(msg, "sending this");
    try {
        String msg_received = null;
        System.out.println("TRYING TO CONNECT");

        InetAddress serverAddr = InetAddress.getByName(HOST);

        Socket socket = new Socket(HOST, PORT);

        System.out.println("CONNECTED");

        System.out.println(socket.getLocalAddress());
        OutputStream out = socket.getOutputStream();

        PrintWriter output = new PrintWriter(out);
        output.println(msg);
        output.flush();

        // Get data sent through socket
        DataInputStream DIS = new DataInputStream(socket.getInputStream());


        // read data that got sent
        msg_received = DIS.readUTF();

        System.out.println("Message from server" + msg_received);

        socket.close();


            } catch (Exception e) {
                System.out.println("Did not receive string");
            }




}

}

之后没有任何东西被打印出来
Socket socket = new Socket(HOST, PORT);

我哪里弄错了?

【问题讨论】:

标签: android python sockets


【解决方案1】:

使用Socket 需要应用拥有INTERNET 权限。尝试将此添加到您的manifest.xml

 <uses-permission android:name="android.permission.INTERNET" />

也可以关注this answer了解更多详情。

【讨论】:

    猜你喜欢
    • 2019-11-19
    • 2019-05-26
    • 2018-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多