【发布时间】:2018-01-25 05:51:30
【问题描述】:
我有一个 TCP 服务器应用程序在 Android Studio 中作为一个单独的模块运行。它正在侦听远程 TCP 数据包。运行应用程序的计算机当前已连接到我的局域网。
TcpServer server = new TcpServer();
server.listenForPacket();
这里是TcpServer
public class TcpServer {
private void listenForPacket(){
try{
ServerSocket welcomeSocket =
new ServerSocket(Constants.LOCAL_PORT);
Socket connectionSocket =
welcomeSocket.accept();
// Pauses thread until packet is received
BufferedReader packetBuffer =
new BufferedReader(
new InputStreamReader(
connectionSocket.getInputStream()));
System.out.print("Packet received");
} catch (IOException e){
e.printStackTrace();
}
}
}
我的手机上还有一个单独的应用程序运行 TCP 客户端。手机关闭了wifi,应该通过数据线向服务器发送数据包,最终通过互联网。
TcpClient client = new TcpClient();
client.sendPacket();
这里是TcpClient
public class TcpClient {
private void sendTcpPacket(){
try {
InetAddress remoteInetAddress =
InetAddress.getByName(Constants.PUBLIC_IP_ADDRESS);
InetAddress localInetAddress =
InetAddress.getByName(Constants.LOCAL_IP_ADDRESS);
int remotePort = Constants.FORWARDING_PORT;
int localPort = Constants.LOCAL_PORT;
Socket socket =
new Socket(remoteInetAddress,
remotePort, localInetAddress, localPort);
DataOutputStream dataOutputStream =
new DataOutputStream(socket.getOutputStream());
byte[] packet = new byte[1];
packet[0] = (byte) 255;
dataOutputStream.write(packet, 0, packet.length);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
但是,服务器没有收到客户端发送的数据包。
现在,我假设我的变量是正确的,或者它们是正确的吗?
InetAddress remoteInetAddress =
InetAddress.getByName(Constants.PUBLIC_IP_ADDRESS);
InetAddress localInetAddress =
InetAddress.getByName(Constants.LOCAL_IP_ADDRESS);
int remotePort = Constants.FORWARDING_PORT;
int localPort = Constants.LOCAL_PORT;
我还设置了我的转发端口转发到本地 ip 地址。
不知道为什么数据包没有通过。知道为什么吗?
【问题讨论】:
标签: android networking tcp