首页 文章

对不同网络的不同Android设备使用套接字编程

提问于
浏览
0

我正在开发一个套接字应用程序 .

Background

  • 有两个android设备 .

  • 两个设备都在不同的网络上(即一个在移动网络上,另一个在不同的移动网络或WiFi上) .

  • App在同一个wifi网络上工作正常 .

  • 应用程序无法在不同的网络上运行 .

  • 我读过有关端口转发的信息,但这一切都以路由器端口转发结束,所以这与我的应用程序无关,因为我的应用程序就像在不同的网络上工作一样 .

What I've tried:

I got server ip address using following method and it gives me ip address:

public String getIpAddress() {
    String ip = "";
    try {
        Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
                .getNetworkInterfaces();
        while (enumNetworkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = enumNetworkInterfaces
                    .nextElement();
            Enumeration<InetAddress> enumInetAddress = networkInterface
                    .getInetAddresses();
            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress.nextElement();

                if (inetAddress.isSiteLocalAddress()) {
                    ip += "Server running at : "
                            + inetAddress.getHostAddress();
                }
            }
        }

    } catch (SocketException e) {

        // TODO Auto-generated catch block
        e.printStackTrace();
        ip += "Something Wrong! " + e.toString() + "\n";
    }
    text.setText(ip);
    return ip;
}

我正在使用静态端口8080 [可能这是一个问题,如果是这样,请建议我一个选项] .

我在客户端使用这些行连接,但soket对象在不同的网络上返回null:

InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

socket = new Socket(serverAddr, SERVERPORT);

那么,请建议我应该使用什么来通过不同的网络[应用程序在同一网络上完美运行]在不同的真实Android设备上进行通信?

1 回答

  • 0

    https://en.wikipedia.org/wiki/TCP_hole_punching

    如果您连接到P2P连接,则可以使用此技术 .

    否则,您可以获得两个客户端都可以访问的在线服务器,它可以用于在两者之间转发消息 . 亚马逊网络服务是一个很好的选择,你可以使用带有公共IP的T2.mini机器免费试用一年 .

    https://aws.amazon.com/

相关问题