1
我有一個TCP服務器應用程序作爲Android Studio中的單獨模塊運行。它正在偵聽遠程TCP數據包。該應用程序正在運行的計算機當前已連接到本地局域網。如何通過互聯網接收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地址。
不確定數據包未通過的原因。任何想法爲什麼?