通过互联网的android socket通信 [英] android socket communication through internet

查看:116
本文介绍了通过互联网的android socket通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与Android和Windows之间的socket通信实验。
直到我使用10.0.2.2地址,这是回送其上的模拟器运行的计算机的一切工作正常。但是,如果我给任何其他地址到插座的构造函数的连接超时。
我的目标是通过互联网我的手机和计算机之间的通信。
我也试了一下我的手机上,所以我不认为这是一个防火墙问题。
这里是我的code:

I'm experimenting with socket communication between android and windows. Everything works fine till i use the 10.0.2.2 address which is the loopback to the computer on which the emulator is running. But if i give any other address to the Socket constructor the connection is timing out. My goal is to communicate between my phone and my computer through the internet. I also tried it on my phone, so i don't think that it's a firewall problem. Here is my code:

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());
    }
}

我也在寻找内置函数代替concatenateArrays功能,简单地把两个字节数组在一起一个java。

I'm also looking for a java built in function instead of the concatenateArrays function which simply put two byte array together.

编辑:

对不起,也许我没有提供足够的信息。我已经尽我用于互联网连接和我的LAN IP的外部IP。路由器上的端口转发到我的电脑。所以,如果我写192.168.1.101或代替10.0.2.2是由互联网服务提供商提供的IP,比我无法连接。

Sorry, maybe i not provided enough information. I have already tried my external ip used for the internet connection and my LAN ip. Port on router is forwarded to my computer. So if i write "192.168.1.101" or the ip given by the internet service provider in place of "10.0.2.2", than i cannot connect.

编辑:

好吧,我想通了,这是我的防火墙。

Ok, i figured out it was my firewall.

推荐答案

好吧,我想通了,这是我的防火墙。

Ok, i figured out it was my firewall.

这篇关于通过互联网的android socket通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆