【问题标题】:android socket communication through internet通过互联网的android套接字通信
【发布时间】:2011-11-24 14:17:24
【问题描述】:

我正在试验 android 和 windows 之间的套接字通信。 一切正常,直到我使用 10.0.2.2 地址,该地址是运行模拟器的计算机的环回。但是,如果我向 Socket 构造函数提供任何其他地址,则连接超时。 我的目标是通过互联网在我的手机和我的电脑之间进行通信。 我也在我的手机上试过,所以我不认为这是一个防火墙问题。 这是我的代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    try {
        clientSocket = new Socket("10.0.2.2", 48555);
        Log.d("Offdroid", "socket connected");
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println(e.toString());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println(e.toString());
    }
}

public void connectServer(View button) {
    try {
        String message = "shutdown";
        byte[] messageBytes = message.getBytes("US-ASCII");
        int messageByteCount = messageBytes.length;
        byte[] messageSizeBytes = new byte[2];
        messageSizeBytes = intToByteArray(messageByteCount);

        byte[] sendBytes = concatenateArrays(messageSizeBytes, messageBytes);

        Log.d("Offdroid", Integer.toString(messageSizeBytes.length));

        clientSocket.setReceiveBufferSize(16);
        clientSocket.setSendBufferSize(512);
        OutputStream outStream = clientSocket.getOutputStream();
        //InputStream inStream = clientSocket.getInputStream();

        outStream.write(sendBytes, 0, sendBytes.length);
    } catch(Exception EX) {
        Log.e("Offdroid", EX.getMessage());
    }
}

我也在寻找一个 java 内置函数,而不是 concatenateArrays 函数,它只是将两个字节数组放在一起。

编辑:

抱歉,我可能没有提供足够的信息。我已经尝试过用于互联网连接的外部 ip 和我的 LAN ip。路由器上的端口被转发到我的电脑。因此,如果我写“192.168.1.101”或互联网服务提供商提供的 ip 代替“10.0.2.2”,我将无法连接。

编辑:

好的,我发现这是我的防火墙。

【问题讨论】:

    标签: android sockets


    【解决方案1】:

    Emulator 使用与您的计算机相同的网络,因此它能够将其路由到计算机。但是你的手机要和你的电脑连接,你得给一个不同的IP,基本上就是电脑的IP。

    我猜你正在使用一些共享网络,并获得这个 (10.0.2.2) IP。您的计算机应直接连接到 Internet,才能通过手机运行。

    【讨论】:

    • 抱歉,我可能没有提供足够的信息。我已经尝试过用于互联网连接的外部 ip 和我的 LAN ip。路由器上的端口被转发到我的电脑。因此,如果我写“192.168.1.101”或互联网服务提供商提供的 ip 代替“10.0.2.2”,我将无法连接。
    【解决方案2】:

    好的,我发现这是我的防火墙。

    【讨论】:

      猜你喜欢
      • 2016-05-24
      • 2012-09-13
      • 2014-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多