它只是一个与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 Thread上完成。
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);
我在哪里弄错了?
答案 0 :(得分:0)
使用Socket
要求应用获得INTERNET
权限。尝试将其添加到manifest.xml
:
<uses-permission android:name="android.permission.INTERNET" />
还可以查看this answer了解更多详情。