【发布时间】: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);
我哪里弄错了?
【问题讨论】:
-
去developer.android.com学习Android。
-
抱歉,这不是谷歌翻译代码。先学点Java
-
我不想要完整的翻译,只想要一些关于如何使它工作的想法。