2017-08-16 68 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发送。