如何通过Internet接收TCP数据包

时间:2017-08-16 23:39:16

标签: android networking tcp

我有一个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地址。

不确定为什么数据包没有通过。知道为什么吗?

1 个答案:

答案 0 :(得分:1)

// Pauses thread until packet is received

不,不。

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

这只会创建一个BufferedReader。它不做任何I / O.如果您想阅读,您必须拨打read()方法之一,或者如果您要发送线路,则可能需要readLine()

此外,您没有关闭任何套接字。当您使用DataOutputStream发送时,您应该使用InputStream来接收;或者让BufferedReader接收并使用Writer发送。