【发布时间】:2022-01-21 04:04:09
【问题描述】:
我试图在我的 java 应用程序和 python 客户端之间进行交流。但它似乎无法连接。 我不确定这是否是因为 IP 地址错误。因为我在某处读到您可以使用 PC 的 IP 连接到虚拟设备,但我也使用了虚拟设备的 10.0.x.x 地址,这似乎也不起作用。在 IntelliJ 中,我的代码似乎确实可以工作,只是不适用于应用程序。
我的python客户端代码:
import socket
HOST = "172.20.10.12"
PORT = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
print('connected')
sock.sendall(b'Hello!')
data = sock.recv(1024)
print("1", data, '\n')
sock.sendall(b'Bye\n')
data = sock.recv(1024)
print("2", data, '\n')
print("Socket closed")
sock.close()
这是我的应用程序的接收端:StartReceive.java:
package com.example.test;
import java.io.IOException;
class StartReceive implements Runnable {
@Override
public void run() {
try {
Receive.startReceive();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我的receive.java:
public class Receive {
static String fromClient;
static String toClient;
public static void startReceive() throws IOException {
ServerSocket server = new ServerSocket(8080);
System.out.println("wait for connection on port 8080");
boolean run = true;
while (run) {
Socket client = server.accept();
System.out.println("got connection on port 8080");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
fromClient = in.readLine();
System.out.println("received: " + fromClient);
if (fromClient != null) {
toClient = "message is received on server";
System.out.println("send: message is received");
out.println(toClient);
fromClient = in.readLine();
System.out.println("received: " + fromClient);
if (fromClient.equals("Bye")) {
toClient = "bye received on server";
System.out.println("send: bye received on server");
out.println(toClient);
client.close();
run = false;
System.out.println("socket closed");
}
}
}
}
}
然后我在我的 mainactivity 中这样称呼它:
【问题讨论】:
-
你能告诉我们在服务器端打印什么吗?
-
@markspace 嗨,它会打印到:wait for connection on port 8080
-
如果您无法接受传入连接,则可能是您的防火墙。
-
@markspace 确实可以。你知道怎么解决吗?
标签: python java android-studio server client