为什么我试图从我的Android设备连接到我的电脑上的网络服务器时出现超时?

时间:2016-05-13 13:56:49

标签: java c# android android-studio networking

个人电脑上的网络服务器位于c# 在form1构造函数中:

var ws = new WebServer(
    request => Task.Run(() => SendResponseAsync(request)),
    "http://+:8098/");
    ws.Run();

这两种方法

public static string GetLocalIPAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }
            throw new Exception("Local IP Address Not Found!");
        }

        public void Send(string ipaddress)
        {
            UdpClient client = new UdpClient();
            IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, 15000);
            byte[] bytes = Encoding.ASCII.GetBytes(ipaddress);
            client.Send(bytes, bytes.Length, ip);
            client.Close();
        }

然后在计时器滴答事件间隔设置为1000ms

int countsends = 0;
        private void timer2_Tick(object sender, EventArgs e)
        {
            if (countsends == 10)
            {
                Send(localipadd);
                countsends = 0;
            }
            countsends += 1;
        }

WebServer类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Threading;

namespace Automatic_Record
{
    class WebServer
    {
        private readonly HttpListener _listener = new HttpListener();
        private readonly Func<HttpListenerRequest, Task<string>> _responderMethod;

        public WebServer(string[] prefixes, Func<HttpListenerRequest, Task<string>> method)
        {
            try
            {
                if (!HttpListener.IsSupported)
                    throw new NotSupportedException(
                        "Needs Windows XP SP2, Server 2003 or later.");

                // URI prefixes are required, for example 
                // "http://localhost:8080/index/".
                if (prefixes == null || prefixes.Length == 0)
                    throw new ArgumentException("prefixes");

                // A responder method is required
                if (method == null)
                    throw new ArgumentException("method");

                foreach (string s in prefixes)
                    _listener.Prefixes.Add(s);

                _responderMethod = method;
                _listener.Start();
            }
            catch(AccessViolationException err)
            {
                string error = err.StackTrace;
            }
        }
}

在PC端,c#i没有得到任何错误或异常并且使用断点我可以看到路由器上的网络上的pc ip在方法上发送变量ipaddress它的值是10.0.0.1我还登录到我的路由器设置,我看到电脑是10.0.0.1

现在是android-studio中的java端,我试图获取pc ip并连接到它:

在主要活动的顶部:(我尝试在端口8098之前但它没有工作,所以我尝试了15000但是还没有工作仍然得到超时消息)

private String[] ipaddresses = new String[]{
            "http://10.0.0.1:15000/?cmd=nothing"
            };

然后从onCreate

调用按钮单击方法
@Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addListenerOnButton();
        currentActivity = this;
        initTTS();
    }

addListenerOnButton

public void addListenerOnButton()
    {

        btnClick = (Button) findViewById(R.id.connecttoserverbutton);

        btnClick.setOnClickListener(new OnClickListener()
        {
            byte[] response = null;
            @Override
            public void onClick(View arg0)
            {

                text = (TextView) findViewById(R.id.statusTextView);

                Thread t = new Thread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        for (int i = 0; i < ipaddresses.length; i++)

                        {
                            counter = i;
                            try
                            {
                                response = Get(ipaddresses[i]);
                            }
                            catch (Exception e)
                            {
                                String err = e.toString();
                            }

                            if (response!=null)
                            {


                                try
                                {
                                    final String a = new String(response, "UTF-8");




                                    text.post(new Runnable()
                                    {
                                        @Override
                                        public void run()
                                        {
                                            text.setText(a + " Oמ " + ipaddresses[counter]);
                                        }
                                    });
                                    iptouse = ipaddresses[i].substring(0,ipaddresses[i].lastIndexOf("=")+1);
                                    connectedtoipsuccess = true;
                                    Logger.getLogger("MainActivity(inside thread)").info(a);
                                } catch (UnsupportedEncodingException e)
                                {
                                    e.printStackTrace();
                                    Logger.getLogger("MainActivity(inside thread)").info("encoding exception");
                                }

                                Logger.getLogger("MainActivity(inside thread)").info("test1");
                                break;

                            }
                            else
                            {

                            }





                        }
                        counter = 0;
                        if (response == null)
                        {
                            text.post(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    text.setText("Connection Failed");
                                }
                            });
                        }
                    }
                });
                t.start();
            }
        });

    }

最后获取Get方法

private byte[] Get(String urlIn)
    {
        URL url = null;
        String urlStr = urlIn;
        if (urlIn!=null)
            urlStr=urlIn;

        try
        {
            url = new URL(urlStr);
        } catch (MalformedURLException e)
        {
            e.printStackTrace();
            return null;
        }
        HttpURLConnection urlConnection = null;
        try
        {
            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream in = new BufferedInputStream(urlConnection.getInputStream());

            byte[] buf=new byte[10*1024];
            int szRead = in.read(buf);
            byte[] bufOut;

            if (szRead==10*1024)
            {
                throw new AndroidRuntimeException("the returned data is bigger than 10*1024.. we don't handle it..");
            }
            else
            {
                bufOut = Arrays.copyOf(buf, szRead);
            }
            return bufOut;
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
        finally
        {
            if (urlConnection!=null)
                urlConnection.disconnect();
        }
    }

我的Android设备也连接到路由器上的同一网络,我在路由器设置上检查了我的设备,我看到了我的设备。

我在Get方法中的android-studio端使用了一个断点。 它已经上线了:

InputStream in = new BufferedInputStream(urlConnection.getInputStream());

然后我点击“继续”,这就是它在这里挂起,而是在大约30秒之后继续前往下一行byte[] buf=new byte[10*1024];:{{1} }

android.system.ErrnoException:连接失败:ETIMEDOUT(连接超时) 无法连接到/10.0.0.1(端口15000):连接失败:ETIMEDOUT(连接超时)

我无法在logcat中看到任何异常。

0 个答案:

没有答案