2017-08-16 95 views
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地址。

不確定數據包未通過的原因。任何想法爲什麼?

回答

1
// Pauses thread until packet is received 

不,它不。

BufferedReader packetBuffer = 
    new BufferedReader(
     new InputStreamReader(
      connectionSocket.getInputStream())); 

這只是創建BufferedReader。它不做任何I/O。如果你想閱讀,你必須打電話read()方法之一,或者如果你發送線路,也許readLine(),你不是。

此外,您還沒有關閉任何套接字。而當您使用DataOutputStream發送時,您應該使用InputStream來接收;否則請保留BufferedReader以接收並使用Writer發送。